[Tutorial] Send an e-mail with JavaMail and Gmail

On January 19, 2011, in JavaMail, Tutorial, by lucasterdev

Requirements:

- JavaMail jars

- Jaf jars

All these jars must be in the classpath!

Dependencies:

<dependency>
	<groupId>javax.mail</groupId>
	<artifactId>mail</artifactId>
	<scope>provided</scope>
</dependency>

Code:

package my;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Properties;
import java.util.Date;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Msgsend {

	public static void main(String[] argv) {
		String auth = "true";
		String fallback = "false";
		String debug = "true";

		String port1 = "465";
		String port2 = "25";
		String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

		//Username and password to connect to the SMTP server
		final String username = "AAAAAA";
		final String password = "BBBBBB";

		//E-mail fields
		String to = "XXXXXX";
		String subject = "This is a JavaMail test.";
		String body = "Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah";
		String from = "YYYYYY";
		String cc = null;
		String bcc = null;
		String url = null;
		String mailhost = "smtp.gmail.com";
		String mailer = "Msgsend";

		// Absolute path to the attached file
		String file = null;

		String protocol = null;
		String host = null;

		String record = null; // name of folder in which to record mail

		try {

			// Initialize the JavaMail Session.
			Properties props = System.getProperties();
			// XXX - could use Session.getTransport() and Transport.connect()
			// XXX - assume we're using SMTP
			props.put("mail.smtp.host", mailhost);
			props.put("mail.smtp.auth", auth);
			props.put("mail.debug", debug);
			props.put("mail.smtp.port", port1);
			props.put("mail.smtp.socketFactory.port", port1);
			props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
			props.put("mail.smtp.socketFactory.fallback", fallback);

			// Get a Session object
			Session session = Session.getDefaultInstance(props,
					new javax.mail.Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(username,
									password);
						}
					});

			// Construct the message.
			Message msg = new MimeMessage(session);
			msg.setHeader("X-Mailer", mailer);
			msg.setSentDate(new Date());
			if (from != null)
				msg.setFrom(new InternetAddress(from));
			else
				msg.setFrom();
			msg.setRecipients(Message.RecipientType.TO,	InternetAddress.parse(to, false));
			if (cc != null)
				msg.setRecipients(Message.RecipientType.CC,	InternetAddress.parse(cc, false));
			if (bcc != null)
				msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
			msg.setSubject(subject);
			if (file != null) {
				// Attach the specified file.
				// We need a multipart message to hold the attachment.
				MimeBodyPart mbp1 = new MimeBodyPart();
				mbp1.setText(body);
				MimeBodyPart mbp2 = new MimeBodyPart();
				mbp2.attachFile(file);
				MimeMultipart mp = new MimeMultipart();
				mp.addBodyPart(mbp1);
				mp.addBodyPart(mbp2);
				msg.setContent(mp);
			} else {
				// If the desired charset is known, you can use
				// setText(body, charset)
				msg.setText(body);
			}

			// Send the message.
			Transport.send(msg);

			System.out.println("\nMail was sent successfully.");

			// Save a copy of the message, if requested.
			if (record != null) {
				// Get a Store object
				Store store = null;
				if (url != null) {
					URLName urln = new URLName(url);
					store = session.getStore(urln);
					store.connect();
				} else {
					if (protocol != null)
						store = session.getStore(protocol);
					else
						store = session.getStore();

					// Connect
					if (host != null || username != null || password != null)
						store.connect(host, username, password);
					else
						store.connect();
				}

				// Get record Folder. Create if it does not exist.
				Folder folder = store.getFolder(record);
				if (folder == null) {
					System.err.println("Can't get record folder.");
					System.exit(1);
				}
				if (!folder.exists())
					folder.create(Folder.HOLDS_MESSAGES);

				Message[] msgs = new Message[1];
				msgs[0] = msg;
				folder.appendMessages(msgs);

				System.out.println("Mail was recorded successfully.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
 

Here is the source code you need to build an application with Hibernate+MySQL based authentication mechanism with Spring Security 3.0.5.
Many other tutorials I found focus only on single parts of the security implementation with Spring, BUT this tutorial addresses them all!
You can use this tutorial to build a new application from scratch, or to add security to your existing applications.
With this tutorial you can have your pre-existing “user” entities recognised by the Spring Security framework!
The authentication tables are exactly the ones provided by Spring Security, which provides remarkable integration.
The resulting application will have customisable login form “login.jsp” and redirect to a custom access denied page “accessDenied.jsp“.

Your build path must contain:
- Spring Framework 3.0.5.RELEASE (all jars)
- Spring Security 3.0.5 (all jars)
- Hibernate 3.6.0.FINAL (all jars)
- Commons-logging.jar
- mysql-connector-java-5.1.14-bin.jar

web.xml

<?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">

	<display-name>SpringSecurityTest</display-name>

	<description>
      This is a sample application with Spring Security authentication.
    </description>

	<!--
		We register a filter named springSecurityFilterChain that delegates all requests
		matching the url pattern ‘/*’ to a DelegatingFilterProxy.
	-->
	<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>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
    	<dispatcher>ERROR</dispatcher>
	</filter-mapping>

	<!--
		We configure a listener to load the context of the web application at start up.
		This will load our applicationContext-security.xml file.
		The application context is then available via
		WebApplicationContextUtils.getWebApplicationContext(servletContext).
	-->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
	</context-param>

    <servlet>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value></param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

	<error-page>
		<exception-type>java.lang.Exception</exception-type>
		<location>/util/uncaughtException.jsp</location>
	</error-page>

<!--	 <error-page>-->
<!--        <error-code>403</error-code>-->
<!--        <location>/accessDenied.jsp</location>-->
<!--    </error-page>-->

	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

</web-app>

dispatcherServlet-servlet.xml

<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"
        xsi:schemaLocation="
        	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- ========================== WEB DEFINITIONS ======================= -->

	<!-- <context:component-scan base-package="sst"/> -->

	<!-- <context:annotation-config /> -->

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages"/>
    </bean>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

applicationContext.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"
	xmlns:sec="http://www.springframework.org/schema/security"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

	<!-- ========================= DATASOURCE ======================== -->

	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/springsecuritytest" />
		<property name="username" value="root" />
		<property name="password" value="d9b6j2x" />
	</bean>

	<!-- ========================== HIBERNATE ============================ -->

	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="annotatedClasses">
			<list>
				<value>sst.User</value>
				<value>sst.Authority</value>
			</list>
		</property>
		<property name="annotatedPackages">
		<list>
			<value>sst</value>
		</list>
		</property>
		<property name="hibernateProperties">
			<value>
				hibernate.dialect=org.hibernate.dialect.MySQLDialect
				hibernate.show_sql=true
				hibernate.hbm2ddl.auto=update
			</value>
		</property>
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<tx:annotation-driven transaction-manager="transactionManager" />

	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!-- ========================= BEANS ======================== -->

	<bean id="userDao" class="sst.UserDaoImpl">
		<property name="hibernateTemplate" ref="hibernateTemplate" />
	</bean>

	<bean id="userService" class="sst.UserServiceImpl">
		<property name="userDao" ref="userDao" />
	</bean>

	<!-- ========================= SECURITY ======================== -->

	<sec:http auto-config="true">
		<!-- <sec:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" /> -->
		<sec:intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
		<sec:intercept-url pattern="/member/**" access="ROLE_MEMBER,ROLE_ADMIN" />
		<sec:form-login login-page="/login.jsp" default-target-url="/index.jsp" authentication-failure-url="/loginfail.jsp"/>
		<sec:access-denied-handler ref ="myAccessDeniedHandlerImpl"/>
		<!-- <sec:logout logout-success-url="/index.jsp" /> -->
	</sec:http>

	<!--
		This is a modified AccessDeniedHandler that performs a redirect instead of a forward.
		This way, the address bar updates to the access denied page's URL.
	 -->
	<bean id="myAccessDeniedHandlerImpl" class="org.springframework.security.web.access.MyAccessDeniedHandlerImpl">
		<property name="errorPage" value="/accessDenied.jsp"/>
	</bean>

	<sec:authentication-manager>
		<sec:authentication-provider user-service-ref="userUserDetailsService"/>
	</sec:authentication-manager>

    <bean id="userUserDetailsService" class="sst.UserUserDetailsService">
        <constructor-arg ref="userService"/>
    </bean>

</beans>

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="

http://java.sun.com/xml/ns/persistence

http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

	<persistence-unit name="SpringSecurityTest">
		<class>sst.User</class>
		<class>sst.Authority</class>
	</persistence-unit>

</persistence>

User.java

package sst;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.*;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * The persistent class for the USERS database table.
 *
 */
@Entity
@Table(name="USERS")
public class User implements Serializable, UserDetails {

	private static final long serialVersionUID = 1L;

	//Original props

	@Id
	@Column(name="USERNAME")
	private String username;

	@Column(name="ENABLED")
	private String enabled;

	@Column(name="PASSWORD")
	private String password;

	//bi-directional one-to-one association to Authority
	@OneToOne
	@JoinColumn(name="USERNAME")
	private Authority authority;

	// Getters & Setters for original props

	public String getUsername() {
		return this.username;
	}

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

	public String getEnabled() {
		return this.enabled;
	}

	public void setEnabled(String enabled) {
		this.enabled = enabled;
	}

	public String getPassword() {
		return this.password;
	}

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

	//Getters and setters for relation property

	public Authority getAuthority() {
		return this.authority;
	}

	public void setAuthority(Authority authority) {
		this.authority = authority;
	}

	//Spring Security props

	private transient Collection<GrantedAuthority> authorities;

    //UserDetails methods

    @Transient
    public Collection<GrantedAuthority> getAuthorities() {  return authorities;}

    @Transient
    public boolean isAccountNonExpired() { return true;}

    @Transient
    public boolean isAccountNonLocked() { return true; }

    @Transient
    public boolean isCredentialsNonExpired() {return true; }

    @Transient
    public boolean isEnabled() {
        return getEnabled().equals("true");
    }

    @Transient
    public void setUserAuthorities(List<String> authorities) {
        List<GrantedAuthority> listOfAuthorities = new ArrayList<GrantedAuthority>();
        for (String role : authorities) {
            listOfAuthorities.add(new GrantedAuthorityImpl(role));
        }
        this.authorities = (Collection<GrantedAuthority>) listOfAuthorities;
    }

    //Constructors

    public User() {
    }

}

Authority.java

package sst;

import java.io.Serializable;
import javax.persistence.*;

/**
 * The persistent class for the AUTHORITIES database table.
 *
 */
@Entity
@Table(name="AUTHORITIES")
public class Authority implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@Column(name="USERNAME")
	private String username;

	@Column(name="AUTHORITY")
	private String authority;  //Spring Security demands them to start with "ROLE_"

	//bi-directional one-to-one association to User
	@OneToOne(mappedBy="authority")
	private User user;

    public Authority() {
    }

	public String getUsername() {
		return username;
	}

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

	public String getAuthority() {
		return this.authority;
	}

	public void setAuthority(String authority) {
		this.authority = authority;
	}

	public User getUser() {
		return this.user;
	}

	public void setUser(User user) {
		this.user = user;
	}

}

UserDao.java

package sst;

import java.util.List;

public interface UserDao {

	public User getUserByUserName(String userName);

	List<String> getAuthoritiesByUserName(String userName);
}

UserDaoImpl.java

package sst;

import java.util.ArrayList;
import java.util.List;
import sst.User;

import org.springframework.orm.hibernate3.HibernateTemplate;

public class UserDaoImpl implements UserDao {

	HibernateTemplate hibernateTemplate;

	private String queryString = "from User where username = ?";

	public void setHibernateTemplate(HibernateTemplate arg0) {
		hibernateTemplate = arg0;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Override
	public User getUserByUserName(String userName) {
		return (User) hibernateTemplate.find(queryString, userName).get(0);
	}

	@Override
	public List<String> getAuthoritiesByUserName(String userName) {
		User u = (User) hibernateTemplate.find(queryString, userName).get(0);
		Authority a = u.getAuthority();
		String auth = a.getAuthority();
		List<String> l = new ArrayList<String>();
		l.add(auth);
		return l;
	}

}

UserService.java

package sst;

import java.util.List;

public interface UserService {

	User getUserByUserName(String userName);

	List<String> getAuthoritiesByUserName(String userName);

}

UserService.java

package sst;

import sst.UserDao;
import java.util.List;

public class UserServiceImpl implements UserService {

	UserDao userDao;

	@Override
	public User getUserByUserName(String userName) {
		return userDao.getUserByUserName(userName);
	}

	@Override
	public List<String> getAuthoritiesByUserName(String userName) {
		return userDao.getAuthoritiesByUserName(userName);
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

}

UserUserDetailsService.java

package sst;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class UserUserDetailsService implements UserDetailsService {

	private UserService userService;

	public UserUserDetailsService(UserService userService) {
		this.userService = userService;
	}

	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException, DataAccessException {
		User user;
		try {
			user = userService.getUserByUserName(userName);
		} catch (Exception e) {
			throw new UsernameNotFoundException(
					"getUserByUserName returned null.");
		}
		List<String> authorities = userService
				.getAuthoritiesByUserName(userName);
		user.setUserAuthorities(authorities);
		return (UserDetails) user;
	}

}

MyAccessDeniedHandlerImpl.java

package org.springframework.security.web.access;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.access.AccessDeniedHandler;

/**
 * Implementation of {@link AccessDeniedHandler}.
 * <p>
 * This implementation sends a 403 (SC_FORBIDDEN) HTTP error code. In addition, if an {@link #errorPage} is defined,
 * the implementation will perform a request dispatcher "redirect" (instead of "forward") to the specified error page view.
 * Being a "redirect", the <code>SecurityContextHolder</code> won't remain
 * populated. This is of detriment if the view (or a tag library or macro) wishes to access the
 * <code>SecurityContextHolder</code>. The request scope will also be populated with the exception itself, available
 * from the key {@link WebAttributes.ACCESS_DENIED_403}.
 *
 * @author Luca
 */
@SuppressWarnings("unused")
public class MyAccessDeniedHandlerImpl implements AccessDeniedHandler {
    //~ Static fields/initializers =====================================================================================
    /**
     * @deprecated Use the value in {@link WebAttributes} directly.
     */
    @Deprecated
    public static final String SPRING_SECURITY_ACCESS_DENIED_EXCEPTION_KEY = WebAttributes.ACCESS_DENIED_403;
    protected static final Log logger = LogFactory.getLog(MyAccessDeniedHandlerImpl.class);

    //~ Instance fields ================================================================================================

    private String errorPage;

    //~ Methods ========================================================================================================

    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
            throws IOException, ServletException {
        if (!response.isCommitted()) {
            if (errorPage != null) {
                // Put exception into request scope (perhaps of use to a view)
                request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);

                // Set the 403 status code.
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);

                // redirect to error page.

                /*
                 * This is the original code from the default
                 * org.springframework.security.web.access.AccessDeniedHandlerImpl,
                 * which performs a forward:
                 */
                //RequestDispatcher dispatcher = request.getRequestDispatcher(errorPage);
                //dispatcher.forward(request, response);

                /*
                 * This is my code that performs a redirect:
                 */
                response.sendRedirect(request.getContextPath()+errorPage);
            } else {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
            }
        }
    }

    /**
     * The error page to use. Must begin with a "/" and is interpreted relative to the current context root.
     *
     * @param errorPage the dispatcher path to display
     *
     * @throws IllegalArgumentException if the argument doesn't comply with the above limitations
     */
    public void setErrorPage(String errorPage) {
        if ((errorPage != null) && !errorPage.startsWith("/")) {
            throw new IllegalArgumentException("errorPage must begin with '/'");
        }

        this.errorPage = errorPage;
    }
}

MySQL_setup.sql

CREATE DATABASE IF NOT EXISTS springsecuritytest;

USE springsecuritytest;

CREATE TABLE IF NOT EXISTS USERS (
  USERNAME varchar(45) NOT NULL,
  PASSWORD varchar(45) DEFAULT NULL,
  ENABLED enum('true','false') DEFAULT 'true',
  PRIMARY KEY (USERNAME)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS AUTHORITIES(
  USERNAME varchar(45) NOT NULL,
  AUTHORITY varchar(45) DEFAULT NULL,
  PRIMARY KEY (USERNAME),
  FOREIGN KEY (USERNAME) REFERENCES USERS(USERNAME) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;

INSERT INTO USERS (USERNAME, PASSWORD, ENABLED) VALUES ('marco', '123', 'true');
INSERT INTO USERS (USERNAME, PASSWORD, ENABLED) VALUES ('pino', '123', 'true');

INSERT INTO AUTHORITIES (USERNAME, AUTHORITY ) VALUES ('pino', 'ROLE_ADMIN');
INSERT INTO AUTHORITIES (USERNAME, AUTHORITY ) VALUES ('marco', 'ROLE_MEMBER');

accessDenied.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>ACCESS DENIED</title>
	</head>
	<body>
		<p>Access denied. You don't have the required permissions to visit that page.</p>
		<p><a href="member/memberPage1.jsp">Go to Member page 1</a></p>
		<p><a href="admin/adminPage1.jsp">Go to Admin page 1</a></p>
		<p><a href="index.jsp">Go to Index page</a></p>
	</body>
</html>

/admin/adminPage1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!-- This is needed for the logout to work properly. -->
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>ADMIN PAGE 1</title>
	</head>
	<body>
		<p>This is an admin page.</p>
		<p><a href='<spring:url value="/j_spring_security_logout" htmlEscape="true" />'>Logout</a></p>
		<p><a href="../member/memberPage1.jsp">Go to Member page 1</a></p>
		<p><a href="adminPage1.jsp">Go to Admin page 1</a></p>
		<p><a href="../index.jsp">Go to Index page</a></p>
	</body>
</html>

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>INDEX</title>
	</head>
	<body>
		<p>This is the index page.</p>
		<p><a href="member/memberPage1.jsp">Go to Member page 1</a></p>
		<p><a href="admin/adminPage1.jsp">Go to Admin page 1</a></p>
		<p><a href="index.jsp">Go to Index page</a></p>
	</body>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ page import="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"%>
<%@ page import="org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter"%>
<%@ page import="org.springframework.security.core.AuthenticationException"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Login Page</title>
	</head>
	<body>
		<form action="j_spring_security_check" method="POST" >
			<label for="j_username">Username</label>
			<input type="text" name="j_username" id="j_username"/>
			<br/>
			<label for="j_password">Password</label>
			<input type="password" name="j_password" id="j_password" />
			<br/>
			<input type='checkbox' name='_spring_security_remember_me' /> Remember me on this computer.
			<br/>
			<input type="submit" value="Login" />
		</form>
		<p><a href="member/memberPage1.jsp">Go to Member page 1</a></p>
		<p><a href="admin/adminPage1.jsp">Go to Admin page 1</a></p>
		<p><a href="index.jsp">Go to Index page</a></p>
	</body>
</html>

loginfail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>LOGIN FAILED</title>
	</head>
	<body>
		<p>Login failed.</p>
		<p><a href="member/memberPage1.jsp">Go to Member page 1</a></p>
		<p><a href="admin/adminPage1.jsp">Go to Admin page 1</a></p>
		<p><a href="index.jsp">Go to Index page</a></p>
	</body>
</html>

/member/memberPage1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!-- This is needed for the logout to work properly. -->
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>MEMBER PAGE 1</title>
	</head>
	<body>
		<p>This is a member page.</p>
		<p><a href='<spring:url value="/j_spring_security_logout" htmlEscape="true" />'>Logout</a></p>
		<p><a href="memberPage1.jsp">Go to Member page 1</a></p>
		<p><a href="../admin/adminPage1.jsp">Go to Admin page 1</a></p>
		<p><a href="../index.jsp">Go to Index page</a></p>
	</body>
</html>

/util/uncaughtException.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<!-- This page will be shown in the browser if an exception is thrown that is not caught by the application. -->

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>EXCEPTION</title>
	</head>
	<body>
		<h2>Internal error</h2>
		<%
		try {
			// The Servlet spec guarantees this attribute will be available
			Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception"); 

			if (exception != null) {
				if (exception instanceof ServletException) {
					// It's a ServletException: we should extract the root cause
					ServletException sex = (ServletException) exception;
					Throwable rootCause = sex.getRootCause();
					if (rootCause == null)
						rootCause = sex;
					out.println("** Root cause is: "+ rootCause.getMessage());
					rootCause.printStackTrace(new java.io.PrintWriter(out));
				}
				else {
					// It's not a ServletException, so we'll just show it
					exception.printStackTrace(new java.io.PrintWriter(out));
				}
			}
			else  {
		    	out.println("No error information available");
			} 

			// Display cookies
			out.println("\nCookies:\n");
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
		    	for (int i = 0; i < cookies.length; i++) {
		      		out.println(cookies[i].getName() + "=[" + cookies[i].getValue() + "]");
				}
			}

		} catch (Exception ex) {
			ex.printStackTrace(new java.io.PrintWriter(out));
		}
		%>

	</body>
</html>
 

ObjectAid – http://www.objectaid.com

UML2 Tools 0.9.0 All-in-one
Which requires:
org.eclipse.emf.ocl-update.zip

Eclipse ERD (you must manually unzip it into eclipse folder)

STS 2.5.1 (bookmarks to import) But in the group Extensions / STS install only SpringSource Tool Suite Maven Support. Also, do NOT install Core /dm Server Tools.

JBoss Tools 3.2 Nightly Build (it also contains Maven)

m2eclipse Core

m2eclipse Extras

Topcased (it’s the modeled editor embedded in MyEclipse) – http://topcased-mm.gforge.enseeiht.fr/release/update-site3.6/
which requires:

EMF – http://download.eclipse.org/modeling/emft/updates/

EPF Composer – http://www.eclipse.org/epf/downloads/tool/tool_downloads.php
Download both EPF composer (about 78Mb), and EPF Richtext Feature (about
500Kb). Then follow the instructions to install it on a linux based
Eclipse.

SmartQVT – http://sourceforge.net/projects/smartqvt/

org.eclipse.emf.ocl-update.zip
 
 

How to add a Maven repository in Eclipse

On January 11, 2011, in Eclipse, Maven, by lucasterdev

1. Choose the menu item, Window–>Show View–>Other
2. Select “Maven Indexes” and click OK
3. The Maven Indexes tab now appears at the bottom of the Eclipse workbench.
4. Right click the Maven Indexes view tab and select Add Index. The “Add Repository Index” dialog appears.
5. Fill in the Repository URL and Repository Id fields. Click OK.
6. The new repository now appears in the Maven Indexes list, but you need to wait for a lot of time before the index contents are fully populated (check the status bar in the bottom right corner). Eclipse may seem to freeze as well. If any errors occur while updating the new index, these will appear in the Console tab.

 

I found a possible solution here:

http://stackoverflow.com/questions/2782066/maven-archetype-for-simple-servlet-application

But that method doesn’t work, because Eclipse doesn’t let you change the Dynamic Project Module facet version after the project has been created.

Instead, try this:

1. Uncheck the Dynamic Web Module facet checkbox and click Apply.
2. Re-check the Dynamic Web Module facet, choose version 2.5 (or 3.0) and click “Further Configuration”.
3. In the Content Directory field, type “/src/main/webapp”. Be sure that the “Generate web.xml deployment descriptor” is checked. Click OK.
4. Click Apply, then click OK.

Viola!!!

 
 

Add the following line to the top of the file:

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

Then, surround the desired component with <sec:authorize> tag:

<sec:authorize access="hasRole('ROLE_SUPERVISOR')">
	<!-- Here goes what you want to controll the visibility of.
	In this case, only the users with role 'ROLE_SUPERVISOR'
	can see this component.-->
</sec:authorize>
 

How to get JSF 2.0 to update the address bar

On January 7, 2011, in JSF, JSF 2.0, by lucasterdev

By default, JSF 2 is perform a forward while navigating to another page, it caused the page URL is always one behind :) . For example, when you move from “page1.xhtml” to “page2.xhtml”, the browser URL address bar will still showing the same “page1.xhtml” URL.

To solve this, do one of the folowing:

Append the “?faces-redirect=true” to the end of the “outcome” string returnet by the method invoked by the “action” attribute,

OR

Append the “faces-redirect=true” to the end of the the “action” attribute.

<h:form>
<h:commandButton action="page2?faces-redirect=true" value="Move to page2.xhtml" />
</h:form>

OR (best way)

In the navigation rule, you can enable the page redirection by adding a <redirect /> element within the <navigation-case />.

<navigation-rule>
	<from-view-id>start.xhtml</from-view-id>
		<navigation-case>
			<from-outcome>page2</from-outcome>
			<to-view-id>page2.xhtml</to-view-id>
			<redirect />
		</navigation-case>
</navigation-rule>
 

Fix Eclipse appearance in Ubuntu

On January 7, 2011, in Eclipse, Ubuntu, by lucasterdev

To fix the size of tabs, create a file named .gtkrc-2.0 in your home folder, and paste in the following code;

style "gtkcompact" {
	GtkButton::default_border={0,0,0,0}
	GtkButton::default_outside_border={0,0,0,0}
	GtkButtonBox::child_min_width=0
	GtkButtonBox::child_min_heigth=0
	GtkButtonBox::child_internal_pad_x=0
	GtkButtonBox::child_internal_pad_y=0
	GtkMenu::vertical-padding=1
	GtkMenuBar::internal_padding=0
	GtkMenuItem::horizontal_padding=4
	GtkToolbar::internal-padding=0
	GtkToolbar::space-size=0
	GtkOptionMenu::indicator_size=0
	GtkOptionMenu::indicator_spacing=0
	GtkPaned::handle_size=4
	GtkRange::trough_border=0
	GtkRange::stepper_spacing=0
	GtkScale::value_spacing=0
	GtkScrolledWindow::scrollbar_spacing=0
	GtkTreeView::vertical-separator=0
	GtkTreeView::horizontal-separator=0
	GtkTreeView::fixed-height-mode=TRUE
	GtkWidget::focus_padding=0
}
class "GtkWidget" style "gtkcompact"
style "compact-toolbar"
{
	GtkToolbar::internal-padding = 0
	xthickness = 1
	ythickness = 1
}
style "compact-button"
{
	xthickness = 0
	ythickness = 0
}
class "GtkToolbar" style "compact-toolbar"
widget_class "**" style "compact-button"

To enable menu icons, run the following command in a terminal window:

gconftool-2 --type boolean --set /desktop/gnome/interface/menus_have_icons true

In Ubuntu 12:

To enable menu icons, run the following command in a terminal window:

gsettings set org.gnome.desktop.interface menus-have-icons true
gsettings set org.gnome.desktop.interface buttons-have-icons true