Register Spring custom scope using Java Config

When looking for examples on how to register a custom scope for Spring, almost all of them are using XML based config. For example: http://www.javabeat.net/custom-scope-spring-beans/

In my current project, I don’t use Spring XML configuration, so I needed a way to configure the SimpleThreadScope using Java based configuration.
This can of course be used for all custom scope implementation.

First of all, a BeanFactoryPostProcessor extending class is needed which will called after the BeanFactory is created – i.e. before the Beans are created.

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.support.SimpleThreadScope;

public class CustomScopeRegisteringBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		beanFactory.registerScope("thread", new SimpleThreadScope());
	}
}

In your Spring config, define a Bean with your BeanFactoryPostProcessor using a static (!) method:

import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringConfig {

	@Bean
	public static BeanFactoryPostProcessor beanFactoryPostProcessor() {
		return new CustomScopeRegisteringBeanFactoryPostProcessor();
	}

}

Now the scope “thread” can be used for your Spring components. Optionally, a new annotation may be defined for the new scope:

import org.springframework.context.annotation.Scope;

@Scope("thread")
public @interface ThreadScoped {

}

Your Spring components can now be configured with the @ThreadScoped annotation as follows:

@Service
@ThreadScoped
public class MyService {

}
Posted in Configuration, Spring | Leave a comment

Preemptive authentication using wget on Linux

Recently I had a problem when consuming a Secured REST Service using wget on Linux. The Server is running Spring Security 3.1 using HTTP Basic authentication. During development we were using RestClient to consume the REST Service. This Tool, written in Java, internally uses Apache Commons HttpClient for all HTTP Connections. For the authentication part, RestClient has a checkbox labelled “Preemptive?” which is enabled by default.

This worked very well, but the first tests using wget failed because Spring Security couldn’t authenticate the request. Using google to find an answer for this was no help.

The reason is, because only HttpClient calls this kind of behavior as “Preemptive”, wget calls this flag “–auth-no-challenge”. Add this to your wget call and it should work. The manpage of wget describes the flag as follows:

If this option is given, Wget will send Basic HTTP authentication
information (plaintext username and password) for all requests,
just like Wget 1.10.2 and prior did by default.

Use of this option is not recommended, and is intended only to
support some few obscure servers, which never send HTTP
authentication challenges, but accept unsolicited auth info, say,
in addition to form-based authentication.

Posted in Uncategorized | Leave a comment

Wazapp “server fail too many” error

Please Note: Right now (Jan. 11 2013) the activation process using Wazapp 0.9.17 works, so there is no need for the workaround described below.

Recently I bought a Nokia N9 Meego smartphone. After updating it to PR 1.3 I wanted to install WhatsApp as I was using it quite heavily on my Android phone.

As there is no official support for MeeGo, I tried the public beta version of Wazapp. My problem was that I couldn’t register my phone number using Wazapp, always getting the infamous “server fail too many” error.

After trying a lot solutions I found on the internet, I almost gave up, nothing was working at all.

Then I found something in a german forum (http://opensmartpad.de/forum/meego-apps/39360-wazapp-funktioniert-nicht.html#39395) and thought this might be interesting for non-german speakers too 🙂 . It works on Windows but it should work on Mac, as the application is available for Mac too.

The application I’m talking about is “BlueStacks”, an Android Emulator for Windows and Mac. You can download a trial version from the official website at http://bluestacks.com/.

After downloading, installing and starting BlueStacks, install “WhatsApp” from the righthand side menu of BlueStacks.

Then start the usual registration process for WhatsApp. Use the phone number of the SIM card you have in your Nokia N9. The app then tries to send 2 text messages, which will obiously fail, as there is no (virtual) SIM-card present in BlueStacks. This step will take up to 10 minutes (you’ll see a countdown).

I got the text message with my 3-digit activation code after about 6 minutes. But I also read that some people had to wait for the countdown to complete and then use the voice activation which will be suggested after the text message verification failed (expectedly).

To manually enter the activation in Wazapp, start the application and try the usual text message activation procedure. I got the error message that the activation request was too soon, which can be ignored. Just press the “Enter the code manually” button and use the 3-digit activation code from the text message.

After the activation procedure, the app has to be restarted and the contacts have to be synced.

This worked for me, I can’t guarantee it’ll work for anybody else, but as I tried everything else this could be the solution for at least some people.

Please leave a comment if it worked for you or not!

Update Dec. 29 2012:
Apparently Whatsapp has somehow changed the activation process and changed the activation code to be 6 digits instead of 3. Could anyone check if the newest version of Wazapp works with the new activation process? (I can’t test this right now because my N9 is currently being repaired)

Update Jan. 11 2013:
Today I got my N9 back and tested the current version of Wazapp (0.9.17) and it worked right out of the box. The activation process worked flawlessly, so there is no need right now for the BlueStacks workaround.

Regarding the 6 digit code instead of 3 digits: Just enter the 6 digits manually without the  “-” and it should work.

Posted in Uncategorized | 34 Comments

JSF2: Validate number of activated checkboxes

In a project I needed to validate, if the number of selected checkboxes is within a given range. For some particular reason, I couldn’t use a “SelectManyCheckbox” with a custom validator attached (see http://stackoverflow.com/questions/6827675/how-to-validate-the-maximum-amount-of-checked-values-of-a-selectmanycheckbox-bas).

Based on the OmniFaces “ValidateMultipleFields”-Class, I created a validator-component  named “MinMaxSelectionValidator”. See http://pastebin.com/3qL8TL5r for the full source code.

The usage is exactly the same as the validateAll-Validator from omnifaces: http://showcase-omnifaces.rhcloud.com/showcase/validators/validateAll.xhtml

If you have any ideas for improvements, don’t hesitate to comment below.

Posted in Uncategorized | Leave a comment

PrimeFaces partial input validation

PrimeFaces provides a very nice and easy way to do partial input validation of forms.

<h:form>
    <p:inputText value="#{bean.name}" id="name">
        <p:ajax event="blur" process="@this" update="nameMsg" />
    <p:message for="name" id="nameMsg"/>
</h:form>

The validation constraints can either be defined the classic JSF-way (not recommended) or using JSR303 Bean Validation Annotations.
But keep in mind if you have any cross-validation, this could lead to failed validations, as there is only the one inputText processed.

Posted in Uncategorized | 2 Comments

PrimeFaces Datatable Lazyloading using Hibernate Criteria API

The following method is used within a DAO-Class which corresponds to the load-Method of PrimeFaces LazyDataModel as seen in the Showcase: http://www.primefaces.org/showcase/ui/datatableLazy.jsf

@Override
 @Transactional(propagation = Propagation.REQUIRED)
 public List<Car> lazyLoad(int index,
 int count, String sortField, boolean sortOrder,
 Map<String, String> filters) {
Session s = sf.getCurrentSession();

 Criteria crit = s.createCriteria(Car.class);

 if (sortField != null && !sortField.isEmpty()) {
 if (sortOrder) {
 crit = crit.addOrder(Order.asc(sortField));
 } else {
 crit = crit.addOrder(Order.desc(sortField));
 }
 }

 if (!filters.isEmpty()) {
 Iterator<Entry<String, String>> iterator = filters.entrySet().iterator();
 while (iterator.hasNext()) {
 Entry<String, String> entry = iterator.next();
 crit = crit.add(Restrictions.like(entry.getKey(), entry.getValue(), MatchMode.START));
 }
 }

 crit = crit.setFirstResult(index)
 .setMaxResults(count);

 List<Car> result = crit.list();
}

For the rowCount-property of the lazyDataModel you can use the rowCount Projection:

@Override
 @Transactional(propagation = Propagation.REQUIRED)
 public Long getCarCount() {
 Session s = sf.getCurrentSession();

 Criteria crit = s.createCriteria(Car.class)
 .setProjection(Projections.rowCount());

 return crit.list().get(0);
 }
Posted in Uncategorized | 6 Comments

JSF 2.0: actionListener vs. action

Today I had a problem with a PrimeFaces-CommandButton which has a setPropertyActionListener and an actionListener attached to it.

The problem was that the actionListener is called before the setPropertyActionListener, which resulted in the behavior that the Method could only access the set property the second time it got executed.

Replacing the actionListener with an action did the trick (while the action-Method returns null, so there’s no page-transition).

I still don’t know if this is an expected behavior, but it does work, so I’ll stick with this for now.

JSF Implementation is Mojarra 2.0.4-b09 with PrimeFaces 2.2.1

Posted in Uncategorized | 2 Comments

PrimeFaces 2.2.1 and Internet Explorer 8

Internet Explorer Problems – Chapter 231233

As I develop my Web-Applications on Linux, I don’t test it on Internet Explorer too often. To be honest, I even forget about it sometimes. And this was a serious mistake as I had to discover today.

I’m currently developing an application using Spring, JSF2 and PrimeFaces 2.2.1. The application runs perfectly on Firefox, Chrome and Opera. But when I tried to use it on Windows 7 with Internet Explorer 8, I ran into a bunch of Error-Messages that – as you can imagine – provide no information about the problem at all.

The error message was (with alternating Line numbers):

Message: Object doesn’t support this property or method
Line: 105867085
Char: 1
Code: 0
URI: http://localhost:8080/faces/main.xhtml

This error(s) prevented most of my commandButtons to send Ajax Requests, so the application was useless.

After ~4-5 hours of investigating, I discovered the root of the problem:

On some components (basically all that have a widgetVar-Value), I used the same value for “id” and for “widgetVar”!

As simple as this might sound, I still don’t really get, why this is a problem… But anyways, keep this in mind when developing with PrimeFaces!

Posted in Uncategorized | Tagged | 6 Comments

How to register a custom ScriptSessionListener in DWR

In order to register a ScriptSessionListener, one has to get access to DWR’s ScriptSessionManager, which provides a Method “addScriptSessionListener(ScriptSessionListener)”.

To get a reference to the ScriptSessionManager, use the following code:

Container container = ServerContextFactory.get().getContainer();
 ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);
manager.addScriptSessionListener(new MyScriptSessionListener());

A custom ScriptSessionListener could look like this:

public class MyScriptSessionListener implements org.directwebremoting.event.ScriptSessionListener {
 @Override
 public void sessionCreated(ScriptSessionEvent arg0) {
 System.out.println("ScriptSession created " + arg0.getSession().getId());
 }
 @Override
 public void sessionDestroyed(ScriptSessionEvent arg0) {
 System.out.println("ScriptSession destroyed " + arg0.getSession().getId());
 }
}

Posted in Uncategorized | Tagged | 2 Comments

Listening for Session Creation and Destruction on Tomcat

I came up with this while trying to find an easy way to track session creation and destruction of Tomcat 6 without changing any code of my application.

First of all, we need to implement a Listener-Class:

public class SessionListener implements HttpSessionListener {
Logger logger = LoggerFactory.getLogger(this.getClass());

@Override
public void sessionCreated(HttpSessionEvent se) {
logger.info("Session created '"+ se.getSession().getId() + "'");
}
@Override
 public void sessionDestroyed(HttpSessionEvent se) {
logger.info("Session destroyed '"+ se.getSession().getId() + "'");
}

Now we need to register this Listener with Tomcat. To do so, add the following code to your web.xml:

<listener>
 <listener-class>your.package.SessionListener</listener-class>
 </listener>

There you go!

Posted in Uncategorized | Tagged | Leave a comment