Archive for the ‘Hands on’ Category

Handler Interceptors For Annotation Based Configuration in Spring

September 28, 2009

Here’s what you need to have in your *-servlet.xml file:

<context:annotation-config />
<context:component-scan base-package="com.travelfusion.tfweb.guide.controller" />

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
   <property name="interceptors">
      <ref bean="myInterceptor" />
   </property>
</bean>

<bean id="myInterceptor" class="com.company.MyInterceptor">
  <property name="openingTime"><value>9</value></property>
  <property name="closingTime"><value>18</value></property>
</bean>

And your interceptor class something like:

public class MyInterceptor implements HandlerInterceptor {
   private int openingTime;
   private int closingTime;

   @Override
   public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws    Exception {
      // TODO Auto-generated method stub
   }

   @Override
   public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws    Exception {
      // TODO Auto-generated method stub
   }

   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        Calendar cal = Calendar.getInstance();
        int hour = cal.get(HOUR_OF_DAY);
        if (openingTime <= hour < closingTime) {
           return true;
        } else {
           response.sendRedirect("http://host.com/outsideOfficeHours.html");
           return false;
        }
   }
}

Fixing Eclipse Tomcat Timeout

September 28, 2009

To fix “Server Tomcat v6.0.18 was unable to start within 10 seconds. If the server requires more time, try increasing the timeout in the server editor” double click you server in the Servers perspective and increase the timeout value to complete server operations like in the image below.

Picture 3

Software Development Tools

September 15, 2008

I have used the tools listed below for software development, debugging, testing and for editing images for user interfaces. :) Hope you find them useful too!

XMLSpy

Altova® XMLSpy® is the industry’s best selling XML editor and XML development environment, with advanced functionality for modeling, editing, and debugging XML Schema, DTD, XSLT 1.0/2.0, XQuery, SOAP, WSDL, Office Open XML (OOXML), and more. XMLSpy provides multiple editing views, entry helpers, wizards, comprehensive validation and error-handling, and a host of debugging and testing utilities. Code gen in Java, C#, and C++, plus Visual Studio and Eclipse integration, let you develop the most advanced XML and Web services apps for the environment of your choice.

SoapUI

SoapUI is Free and Open Source and is used for Inspecting Web Services, Invoking Web Services, Developing Web Services, Web Service Simulation and Web Service Mocking and Functional Testing of Web Services Load Testing of Web Services over HTTP.

Fiddler (HTTP)

Fiddler is a HTTP Debugging Proxy which logs all HTTP traffic between your computer and the Internet. Fiddler allows you to inspect all HTTP Traffic, set breakpoints, and “fiddle” with incoming or outgoing data. Fiddler includes a powerful event-based scripting subsystem, and can be extended using any .NET language.

SQLYog

SQLyog MySQL GUI is the most powerful MySQL manager and admin tool, combining the features of MySQL Query Browser, Administrator, phpMyAdmin and various other MySQL Front Ends and MySQL clients in a single intuitive interface.

Notepad++

Notepad++ is a free (as in “free speech” and also as in “free beer”) source code editor and Notepad replacement that supports several languages. It runs in the MS Windows environment.

MultipleIEs

Usefull for testing web application in different versions of IE in only one machine.

GIMP

GIMP is the GNU Image Manipulation Program. It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.

Tortoise SVN

TortoiseSVN is a really easy to use Revision control / version control / source control software for Windows. Since it’s not an integration for a specific IDE you can use it with whatever development tools you like. TortoiseSVN is free to use. You don’t need to get a loan or pay a full years salary to use it.

No more ‘LazyInitializationException’ in your integration tests

July 16, 2008

Below an example of what you need to do using JUnit 4 to prevent ‘LazyInitializationException’.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { “classpath:application-context-test.xml” })
public class AccountServiceIntregrationTests extends
AbstractTransactionalJUnit4SpringContextTests {

protected static final String SESSION_FACTORY = “sessionFactory”;

protected static ApplicationContext ctx =
new ClassPathXmlApplicationContext(
“classpath:application-context-test.xml”);

protected static SessionFactory sessionFactory;

@Autowired
private AccountService accountService;

@BeforeClass
public static void oneTimeSetUp() throws Exception {
sessionFactory = (SessionFactory) ctx.getBean(SESSION_FACTORY);
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
session.setFlushMode(FlushMode.MANUAL);
TransactionSynchronizationManager.bindResource(sessionFactory,
new SessionHolder(session));
}

@AfterClass
public static void oneTimeTearDown() throws Exception {
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager
.unbindResource(sessionFactory);
SessionFactoryUtils.closeSession(sessionHolder.getSession());
}

@Test
public void testCreateAccount() {

// Do you test here.

}

}

Cheers,

Ana

Localization with Spring 2.5

July 11, 2008

Hello,

In Spring 2.5 you can tell in your dispatcher servlet configuration to scan for @Controller annotations. That way you don’t configure URL mappings explicity in the dispacher servlet as you used to do before since the annotations are added to the controller classes themselves. It’s less XML and I really like it. However I did not know how to add the locale interceptor in this case, because  there was no urlMapping bean defined. I found out online you just need to add the following configuration to the dispatcher servlet.

<bean     class=”org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping”>
<property name=”interceptors” ref=”localeChangeInterceptor” />

</bean>

Hope this helps you too.

Implementing remember me services with Acegi

September 6, 2007

Today I found an article that helped me implementing the remember me functionality when the user signs into my application. I wanted to add a checkbox below the sign in form, to let the user decide if he wants his credentials to me remembered. This article explains it very well so I though I shared it with you: How to implement remember me using acegi.

Loading multiple property files

August 28, 2007

To load multiple property files using Spring’s PropertyPlaceholderConfigurer, add <property name=”ignoreUnresolvablePlaceholders” value=”true” /> to the one that is loaded first like so:

<bean id=”propertyConfigurer”
class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”>
<property name=”location” value=”classpath:jdbc.properties” />
<property name=”ignoreUnresolvablePlaceholders” value=”true” />
</bean>

<bean id=”mailPropertyConfigurer”
class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”>
<property name=”location” value=”classpath:mail.properties” />
</bean>

This will make sure both files are loaded. :)

Unable to compile class for JSP

August 25, 2007

If you run you web application with the Jetty eclipse plug-in it might happen that you get a”Unable to compile class for JSP” when you try to access the application in your browser. If this happens, go to the properties of your project, select ‘Java Build Path’ and ‘Add External JARs’. You need to add the ‘tools.jar’ file, which is in the ‘lib’ folder of your JDK. Good luck!

How to make Expression Language Work

June 28, 2007

In web.xml use the following header:

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

In your JSPs include the directive:

<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core”%>

Now you can use EL code in your JSP like for example ${user.name}.

Note: You need a JSP 2.0 container.

How to fix LazyInitializationException

May 27, 2007

I wanted to show the number of items in a certain category and what I get is a LazyInitializationException (failed to lazily initialize a collection of role – no session or session was closed). It seems that because the fetch mode for the collection items is lazy, the session is not available anymore when I actually need it.

The solution is to add an interceptor to the UrlHandlerMapping in the dispatcher servlet like so:

<bean id="urlMapping"
  class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="interceptors">
      <list>
        <ref bean="openSessionInViewInterceptor" />
     </list>
    </property>
   <!-- ... -->
</bean>

That interceptor is a OpenSessionInViewInterceptor which will make the session available in the view layer.

<bean name="openSessionInViewInterceptor"
  class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
    <property name="sessionFactory">
      <ref bean="sessionFactory" />
    </property>
</bean>