Friday, January 29, 2016

Spring Security: Redirecting to original URL after login

Its simple, monkey friends.

Your springContext.xml file:
Note: always-use-default-target="false" and authentication-success-handler-ref="authenticationSuccessHandler"
...
       <s:http auto-config='true'>
  <s:intercept-url pattern="/secure/**" access="ROLE_WEBUSER" />
  <s:form-login always-use-default-target="false" 
                login-processing-url="/j_spring_security_check"
             login-page="/index.html" 
             authentication-failure-handler-ref="authenticationFailureHandler" 
             authentication-success-handler-ref="authenticationSuccessHandler"
             default-target-url="/secure/alert.html" />
  <s:logout logout-url="/j_spring_security_logout" logout-success-url="/index.jsp" />
  <s:access-denied-handler error-page="/index.html" />
 </s:http>

        <bean id="authenticationSuccessHandler" class="monkey.web.springsecurity.AuthSuccessHandler" />
...


Your class:
package monkey.web.springsecurity;

import java.io.IOException;

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

import org.apache.log4j.Logger;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

import works.deepdata.deepalert.util.DeepAlertConstants;
import works.deepdata.deepalert.util.StringUtils;

public class AuthSuccessHandler implements AuthenticationSuccessHandler {
    
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    private static Logger logger = Logger.getLogger(AuthSuccessHandler.class);
    
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            org.springframework.security.core.Authentication authentication) throws IOException, ServletException {
        logger.debug("After successful auth...");        
        String targetUrl = determineTargetUrl(request, response);        
        if (response.isCommitted()) {
            logger.error("Response has already been committed. Unable to redirect to " + targetUrl);
            return;
        }
        redirectStrategy.sendRedirect(request, response, targetUrl);
    }
    
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
        SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
        if (savedRequest != null) {
            String targetUrl = savedRequest.getRedirectUrl();
            if (StringUtils.isNotNullOrBlank(targetUrl)) {
                logger.debug("Redirecting to: "+targetUrl);
                return targetUrl;
            }
        }
        return DeepAlertConstants.DEFAULT_AUTH_URL;
    }
}

Thursday, September 5, 2013

Android - Displaying Formatted Text

Bugging me for a while but all you do is:

Step 1: Format the Java String as html
   String formattedMessage = document.replaceAll("(\\r|\\n)", "<br/>");
   formattedMessage = formattedMessage.replaceAll("\\s", "&nbsp;");

Step 2: Display the text in a pre tags
    StringBuilder sb = new StringBuilder();
    sb.append("<html><body><pre>");
    sb.append(formattedMessage);
    sb.append("</pre></body></html>");
    return sb.toString();

Step 3: Display in an AlertDialog using a WebView
   public void showHtml(String html) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setIcon(R.drawable.dialog_information);    
    WebView webView = new WebView(this);
    webView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    webView.loadData(html, "text/html", "utf-8");
    builder.setView(webView);
    builder.show();
  }   

   

Thursday, May 2, 2013

Regular Expressions (Again! Yes, I have forgotten the basics... meh)

So to match a couple of sub-strings, use this: .*(One|Two|Three|Example).*

Monday, October 1, 2012

Now Novel, an online book writing course

For my latest project, please check out the Now Novel website -  it's an online novel writing course designed to get you started quickly.

I had to learn how to program in ruby using ruby on rails (RoR) - I am a Java developer usually, so it was quite a steep learning curve, but very enjoyable. 

I am a new convert to to RoR and was amazed about how quick it was to get a website up and running. For front-end heavy websites, I'd definitely use RoR again. I am really glad that the initial plan of hacking together a WordPress site was abandoned. That would have been php hell!

For more information: I am using Devise for my user registration framework - awesome! Wicked wizard for all the wizards (basically the whole site) and Radar's Forem for the forum. All great libraries that I would recommend to anyone.

Monday, September 27, 2010

GWT: Developer Mode and Spring Contex Listener

I could not get the usual Spring web context listener to work with GWT 2.0.4 in developer mode, running within Eclipse.

Usually the context listener will load the bootstrap Spring files and then parse the classpath to do auowiring, etc. Running the GWT application in Developer mode failed to parse the classpath so any @Autowired annotations threw exceptions with no bean found error message.

The same Spring files loaded fine when loaded "old school way" - IE remove the web context loader listener and use a manual creation of the Spring application context using the same XML files.

Code Change:

In order to get the Developer mode working within Eclipse, I followed what other monkeys had done and nastily copy & paste the GWT class used to start up Developer mode (which is essentially a Jetty-specific class) and made one small change to get it working for Spring classpath parsing.

The class is called com.google.gwt.dev.shell.jetty.JettyLoader
located here: gwt-src-2010-09-02/trunk/dev/core/src (where gwt-src-2010-09-02 is the root of where the GWT code was checked out to from Subversion).

I copy the whole class as a new class called SpringJettyLoader and changed it as follows:
private final ClassLoader bootStrapOnlyClassLoader = new ClassLoader(null) {};
to
private final ClassLoader bootStrapOnlyClassLoader = Thread.currentThread().getContextClassLoader();

I also had to copy the additional class called JettyNullLogger and include it with my new loader class to reduce hassles.

Running GWT Web Application:

A change is required to the Eclipse Run Configuration used to run your GWT web application. Open up the Run Configuration.
On the Server (2nd) tab, uncheck the "Run built-in server" option.
On the Arguments tab, change the current arguments to include your new class as the -server option.
-noserver 
-remoteUI "${gwt_remote_ui_server_port}:${unique_id}" 
-startupUrl PropertyWeb.html 
-server com.tradecraft.property.web.server.jetty.SpringJettyLauncher 
-logLevel INFO 
-war /home/aisling/development/workspaces/workspace2/property-web/war com.tradecraft.property.web.PropertyWeb

Eclipse Classpath:

I was using m2eclipse to do my dependency resolution for me within Eclipse. This ended up being more trouble than it was worth as I kept getting other dependencies includes that I didn't expect. This especially caused issues with Hibernate 3.3.5.FINAL and JPA 1.0 and 2.0.

I ended up putting all my libs in the usual WEB-INF/lib directory and all the other Eclipse projects specifically pointed to those jars.

Eclipse Source Folders Additional Note:

Removing m2eclipse from the projects, left the classes output pointing to /target/classes which is fine but then I attempted to change all the output directories to /bin. The previously added source folders contain to point to the old location and you wonder why nothing works.

It is cleaner to remove all the source folders within each Eclipse project and then re-add them as they then point to where you expect them to.

Thursday, September 16, 2010

GWT: Custom context menu on a Tree

Monkeys, in order to add a custom pop up menu to a tree (or any similar widget I suppose) which is displayed instead of the usual browser's context menu when you right-click on the tree, you can do the following:

Create a Tree class that implements the correct interface for adding a context menu handler:
package com.tradecraft.property.web.client.view.type;

import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.event.dom.client.HasContextMenuHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Tree;

public class MenuContextTree extends Tree implements HasContextMenuHandlers {

  @Override
  public HandlerRegistration addContextMenuHandler(ContextMenuHandler handler) {
    return addDomHandler(handler, ContextMenuEvent.getType());
  }

}

Then add a handler instance to your tree:
public class PropertyTypesAdminScreen extends BaseClientContentScreen {
  ...
  @Override
  public void initScreenUi() {
    tree = new MenuContextTree();
    tree.addContextMenuHandler(new ContextMenuHandler() {      
      @Override
      public void onContextMenu(ContextMenuEvent event) {
        showContextMenu();
        //Don't let the browser display its default context menu
        event.preventDefault();
      }
    });
    mainPanel.add(tree);
  }

  private void showContextMenu() {
    TreeItem selectedTreeItem = tree.getSelectedItem();
    if (selectedTreeItem != null && selectedTreeItem.getUserObject() != null) {
      //do your thing like display a pop up menu
      MenuDialog menuDialog = new MenuDialog(menuBar);
      menuDialog.showRelativeTo(selectedTreeItem);
    }
  }
}


Wednesday, September 15, 2010

Hibernate SQLQuery

In the last week I have seen this error twice when running native SQL queries to a MySQL database using Hibernate. (I am forced to use SQL - not my first choice.)
No Dialect mapping for JDBC type: -1

It took me a while to find the answer, so I thought I would share.

The problem this time is that the data I was retrieving was a longtext column (not a regular varchar) and this is not automatically mapped by the MySQL dialect (I believe this is fixed in Hibernate 3.5).

I solved the problem by using "addScalar" to define the mapping to use. It worked!


Query query = getSession()
.createSQLQuery("select data from form_data where form_data_id = ?")
.addScalar("data", Hibernate.TEXT)
.setInteger(0, formData.getId());
String oldData = ((String)query.uniqueResult());

Hibernate: Parent and Children --> Retrieving Children using a Filter

Same classes as the previous post but this time to avoid an issue with lazy loading the children outside of a closed Hibernate session, load the parent and its children together in the DAO.

This is slightly more complicated as the data model class now has a status attribute (true || false). Either load all the data or only load the data that is active (If a parent is not active, it is not loaded so none of its children is loaded either).

Using the Criteria API, there doesn't seem to be a way to specify a join criteria on the children join.
You can do it easily using a query:
from Cat as cat
left join cat.kittens as kitten
with kitten.bodyWeight > 10.0
Hence the use of a filter when using the Criteria API. The filter either restricts the children to be active or just loads all of them.

@Repository
public class HibernatePropertyTypeDaoImpl extends BaseHibernateDao implements PropertyTypeDao {
  
  private static final String ACTIVE_WHERE_CLAUSE = "where active = true";
  
  private static Logger LOG = LoggerFactory.getLogger(HibernatePropertyTypeDaoImpl.class);

  @Override
  @SuppressWarnings("unchecked")
  public List getCommercialPropertyTypes(boolean onlyActive) {
    List commercialTypes = (List) getPropertyTypesWithoutChildren(CommercialPropertyType.class, onlyActive);
    for(CommercialPropertyType commercialType : commercialTypes) {
      getChildren(commercialType, onlyActive);
    }
    return commercialTypes;
  }
  
  @SuppressWarnings("unchecked")
  private List getPropertyTypesWithoutChildren(Class clazz, boolean onlyActive) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(clazz); 
    criteria.add(Restrictions.isNull("parent"));
    if (onlyActive) {
      criteria.add(Restrictions.eq("active", true));
    }
    criteria.addOrder(Order.asc("id"));
    return criteria.list();
  }

  @SuppressWarnings("unchecked")
  protected void getChildren(CommercialPropertyType type, boolean onlyActive) {
    List children = null;
    if (onlyActive) {
      children = sessionFactory.getCurrentSession()
                               .createFilter(type.getChildren(), ACTIVE_WHERE_CLAUSE)
                               .list();
    } else {
      children = sessionFactory.getCurrentSession()
                               .createFilter(type.getChildren(), "")
                               .list();
    }
    type.setChildren(children);
    LOG.debug("Set children:"+children);
  } 
}

Tuesday, September 14, 2010

Hibernate: Parent and Children

Mapping Model Class:

A single class is used to represent both the parent and children -> CommercialPropertyType.
(The super class PropertyType just provides additional attributes and is not important.)

@Entity
@Table(name = "commercial_property_type")
public class CommercialPropertyType extends PropertyType {

private CommercialPropertyType parent;
private List children;

...

@ManyToOne
@JoinColumn(name = "parent_id")
public CommercialPropertyType getParent() {
return parent;
}

public void setParent(CommercialPropertyType parent) {
this.parent = parent;
}

@OneToMany(cascade = { CascadeType.ALL })
@JoinColumns({ @JoinColumn(name = "parent_id") })
public List getChildren() {
return children;
}

public void setChildren(List children) {
this.children = children;
}
}

Retrieving Data:

Example DAO method to retrieve the top-level parent data with their children data.

@Repository
public class HibernatePropertyTypeDaoImpl extends BaseHibernateDao implements PropertyTypeDao {

@Override
@SuppressWarnings("unchecked")
public List getCommercialPropertyTypes() {
return (List) getPropertyTypesWithChildren(CommercialPropertyType.class);
}

@SuppressWarnings("unchecked")
private List getPropertyTypesWithChildren(Class clazz) {
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(clazz);
//Only get parents
criteria.add(Restrictions.isNull("parent"));
//Get the parent's children if there are any
criteria.createAlias("children", "children", CriteriaSpecification.LEFT_JOIN);
criteria.addOrder(Order.asc("id"));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return criteria.list();
}
}

Thursday, May 6, 2010

Hibernate orderBy gotcha

I just spent the good part of an hour trying to figure out why the "order by" clause in my HQL query was causing a SQLGrammarException "could not execute query".

The SQL worked perfectly, I was stumped. Google couldn't even tell me the answer! I used the time-tested method of try everything and figure out the pattern to solve this one....

The answer was that if you are specifying the "select" clause, the attribute that you are ordering by must appear in the select list.

So, to continue with the example in the hibernate 3.3 documentation
select cat.sex from DomesticCat cat
order by cat.name asc, cat.weight desc, cat.birthdate
is incorrect, but
select cat.sex, cat.name, cat.weight, cat.birthdate from DomesticCat cat
order by cat.name asc, cat.weight desc, cat.birthdate
works.

Thursday, April 22, 2010

Converting an OutputStream to an InputStream

This old problem again... I need an input stream in my test - but how do I create it? This guy knows. Thanks!

final PipedOutputStream pout = new PipedOutputStream();
new Thread(new Runnable(){
public void run(){
DataOutput output = new DataOutputStream(pout);
// write to output stream here
}
}
).start();
DataInputStream in = new DataInputStream(new PipedInputStream(pout));

Tuesday, November 3, 2009

Windows vs Linux

Now I am working on windows again, I have come across the dreaded ^M (windows end of line character)... To strip these characters, on linux, open VI and type :1,$ s/{ctrl-V}{ctrl-M}//

Monday, November 2, 2009

Simple performance logging with Spring

We had a problem recently where a call/response to the server was taking 10 seconds. We needed to figure out where the delay was, and the perfect way to do that was using the Spring PerformanceMonitorInterceptor. With Spring 2.0, adding it is a breeze.

In the applicationContext.xml

<bean id="timingLogger" class="org.springframework.aop.interceptor.PerformanceMonitorInterceptor">

<aop:aspectj-autoproxy>
<aop:config>
<aop:advisor pointcut="execution(* com.yourcompany.application.dao.*.*(..))" ref="timingLogger">
</aop:advisor>
</aop:config>
</aop:aspectj-autoproxy>


and then in log4j.properties

log4j.logger.org.springframework.aop.interceptor.PerformanceMonitorInterceptor=TRACE, stdouttrace
log4j.appender.stdouttrace=org.apache.log4j.ConsoleAppender
log4j.appender.stdouttrace.layout=org.apache.log4j.PatternLayout
log4j.appender.stdouttrace.layout.ConversionPattern=%m%n


We found the problem was not in the application, but with the dev server, which was not configured properly to resolve hosts...

Thursday, October 15, 2009

GWT 1.7 (Hosted Mode): Using a data source

Spring Data Source:
Typically your Spring configuration files specify a data source that is used by your persistence layer to access the physical database.

In order to avoid having to keep changing the data source's details per environment in the Spring config files (dev, test, qa, prod), the easy way is to use a JNDI look up for your data source. Each environment will then be responsible for having the correct data source set up for use.

From the Spring configuration file:
<!-- The data source which is looked up via JNDI -->
  <jee:jndi-lookup id="dataSource" jndi-name="jdbc/MyApp" lookup-on-startup="true" />

Data Source in web application
In the web.xml file, define the data source for use:
<!-- The data source that the application uses to access the current database -->
  <resource-ref>
        <description>The Oracle database data source.</description>
        <res-ref-name>jdbc/MyApp</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
  </resource-ref> 

GWT 1.7 (Hosted Mode):
Since GWT 1,7 uses Jetty to run in hosted mode, you need to set up a Jetty data source so that Spring has its data source to use when the application is run.

Create a file in the /war/WEB-INF folder called jetty-web.xml and define your data source in there:
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN"
"http://jetty.mortbay.org/configure.dtd">
<Configure class="org.mortbay.jetty.webapp.WebAppContext">
  <New id="MyApp" class="org.mortbay.jetty.plus.naming.Resource"> 
    <Arg>jdbc/MyApp</Arg>
    <Arg>
      <New class="oracle.jdbc.pool.OracleDataSource">
        <Set name="user">mast</Set>
        <Set name="password">mast</Set>
        <Set name="URL">jdbc:oracle:thin:@localhost:1521:XE</Set>      
        <Set name="connectionCachingEnabled">true</Set> 
     </New>
    </Arg>
  </New>
</Configure>

Running the GWT Application (Eclipse using Google's GWT Plug-in):
You need to add two Jetty jars to your Eclipse's project classpath, namely:
jetty-name-6.1.x.jar and jetty-plus-6.1.x.jar.
I downloaded Jetty 6.1.19 and used the jars from it.

When you run the application (Right-click the project > Run As > Web Application), you need to modify the Run Configuration slightly.
To modify an existing instance of the application's Run Configuration, use Eclipse's menu option: Run > Run Configurations and select the correct GWT application instance.

On the Arguments tab, add the following VM argument:
-Djava.naming.factory.initial=org.mortbay.naming.InitialContextFactory

Now when you run the application in GWT hosted mode, Spring should have no trouble finding and using the specified data source.

Standalone Mode
Obviously you can do a similar set up for standlone mode (Tomcat or whatever web server you are using) - define the data source in the appropriate way so it is available for the application to use.

Note: the jetty-web.xml file obviously does not need to be deployed with the application into another web container such as Tomcat.

Extjs and Spring Security login.jsp

I went with the GXT-Spring Security approach of a separate login.jsp file, which is all and well, but it required me to worry about styling = booo, bad monkey!

Then, in a flash of inspiration, I decided to try use extjs. It seems there aren't a lot of examples out there of integrating extjs and spring security (formally known as acegi security for the spring framework), so I decided to share mine.

The only problem I face is that when using the ext.Window, I cannot get the username field to get focus. If you have a solution for that, please let me know (I am using extjs 2.0.2)


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ 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" %>

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Emit 1.0</title>

<link type="text/css" rel="stylesheet" href="Emit.css">
<link rel="stylesheet" type="text/css" href="css/gxt-all.css" />
<script type="text/javascript" src="javascript/ext-base.js"></script>
<script type="text/javascript" src="javascript/ext-all.js"></script>

<script>
Ext.onReady(function(){

Ext.QuickTips.init();

/*var viewport = new Ext.Viewport({
layout:'fit',
width:300,
height:150,
plain:true,
items: [{
contentEl: 'loginForm'
}]
});*/

var loginForm = new Ext.form.FormPanel({
formId: 'appLoginForm',
labelWidth: 80,
frame:true,
title:'Emit 1.0 - please login',
defaultType: 'textfield',
monitorValid: true,
keys:[
{
key : Ext.EventObject.ENTER,
fn: function() {
loginForm.getForm().submit();
}
}],
standardSubmit: true,
items:[
{
id: 'message',
xtype: 'box',
autoEl: {cn: '<font color="red"><c:if test="${!empty SPRING_SECURITY_LAST_EXCEPTION.message}">Login failed, please try again.</c:if></font>'}
},
{
fieldLabel: 'Username',
name: 'j_username',
allowBlank: false
},{
fieldLabel: 'Password',
name: 'j_password',
allowBlank: false,
inputType: 'password'
},
new Ext.form.Checkbox({
boxLabel:'Remember me for two weeks',
hideLabel: true,
name:'_spring_security_remember_me',
inputType:'checkbox'
})
],
buttons:[
{
text: 'Login',
type: 'submit',
id: 'submitButton',
formBind: true,
border: true,
handler: function() {
loginForm.getForm().submit();
}
},{
text: 'Reset',
handler: function() {
loginForm.getForm().reset();
}
}]

});

// This just creates a window to wrap the login form.
// The login object is passed to the items collection.
var win = new Ext.Window({
modal: true,
layout:'fit',
width:300,
height:160,
closable: false,
resizable: false,
draggable: false,
plain: true,
border: false,
items: [loginForm]
});
win.show();

loginForm.getForm().findField('j_username').getEl().focus(true);
loginForm.getForm().getEl().dom.action = "j_spring_security_check";

});
</script>

</head>

<body>
<div id="loginForm"></div>
</body>
</html>

Wednesday, October 7, 2009

Spring Security, customizing the access role prefix

Another Spring Security hurdle: when your access specifiers do not start with ROLE_, you will need to customize the RoleVoter and tell it what 'rolePrefix' to use (or not to use in my case).


<beans:bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased">
<beans:property name="decisionVoters">
<beans:list>
<beans:bean id="roleVoter" class="org.springframework.security.vote.RoleVoter">
<beans:property name="rolePrefix" value="PREFIX_HERE" />
</beans:bean>
<beans:bean class="org.springframework.security.vote.AuthenticatedVoter"/>
</beans:list>
</beans:property>
</beans:bean>


To use your custom accessDecisionManager, reference it in the http declaration, like so:

<http auto-config="true" ... access-decision-manager-ref="accessDecisionManager">

Tuesday, October 6, 2009

Spring Security, customizing JdbcUserDetailsManager

I've been working on a Spring Security implementation on GWT (GXT to be exact). I wanted to avoid implementing my own UserDetailsService and rather go with customizing the JdbcUserDetailsManager. However, the javadocs for JdbcUserDetailsManager were a little spare (although I just looked at the parent JdbcDaoImpl and saw the tables are defined there). I had to look in the source code to see what kind of results were required, this is my resulting XML definition.

<beans:bean id="userDetailsManager" class="org.springframework.security.userdetails.jdbc.JdbcUserDetailsManager">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="authenticationManager" ref="authManager" />
<beans:property name="usersByUsernameQuery" value="SELECT user_name, password, 1 FROM users where user_name = ?" />
<beans:property name="authoritiesByUsernameQuery" value="select u.user_name, r.name from users u, role r, user_role ur where ur.user_id = u.user_id and ur.role_id = r.role_id and u.user_name = ?" />
</beans:bean>


Note: the 1 after password indicates the user is enabled.

Thursday, October 1, 2009

GWT server-side integration with Spring (@Autowired)

Old Approach:
Previously we use to load the application's Spring configuration files manually using a custom class (SpringLoader) that was a wrapper around the Spring's ClassPathXmlApplicationContext class. Seemed like an easy way to do things at the time.

All the GWT server-side services would manually look up their required Spring beans which provided the back-end/server tier functionality.
For example:
public class GwtSecurityServiceImpl extends RemoteServiceServlet implements GwtSecurityService {

  /** The service used to check user's access rights and to load user menus. */
  private UserSecurityService userSecurityService = (UserSecurityService) SpringLoader.getBean(SpringBeanId.SECURITY_SERVICE_ID);

public CatchSystemMenu isValidUser(String username, String catchSystem) 
  throws CatchSystemsGwtException {
  ...
  Boolean validUser = userSecurityService.isValidUser(username, catchSystem);
  ...
}


Better Approach:
Use the usual Spring's context listener (defined in the application's web.xml) to load the application's Spring context on application start on.
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:myapp-spring.xml</param-value>
</context-param>
<listener>
  <listener-class>
  org.springframework.web.context.ContextLoaderListener
  </listener-class>
</listener>

Define a base class for all the GWT service classes to extend. This class provides the injection of the Spring managed attributes, using Spring's functionality.

Base GWT service class:
public class SpringRemoteServiceImpl extends RemoteServiceServlet {

  private static final long serialVersionUID = 1L;

  @Override
  public void init() throws ServletException {
    super.init();
    setSpringServices();
  }

  private void setSpringServices() {
    WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
    AutowireCapableBeanFactory beanFactory = ctx.getAutowireCapableBeanFactory();
    beanFactory.autowireBean(this);
  }
}

The individual GWT service classes just extend this class and use the usual Spring @Autowired annotation to inject their Spring-managed attributes.
public class GwtSecurityServiceImpl extends SpringRemoteServiceImpl implements GwtSecurityService {

 /** The service used to check user's access rights and to load user menus. */
 @Autowired
 private UserSecurityService userSecurityService;

 public CatchSystemMenu isValidUser(String username, String catchSystem) 
   throws CatchSystemsGwtException {
 ...
 Boolean validUser = userSecurityService.isValidUser(username, catchSystem);
 ...
 }
}

Nice and easy.
Have a banana.