Older blog entries for waffel (starting at number 18)

How to test spring session or request scope beans


Often you need test cases where you want to use spring configured beans from a existing spring configuration instead of writing mock objects.

In such cases you can use the spring ContextConfiguration class annotation to load your spring configurations. For test cases you may also extend the AbstractTestNGSpringContextTests which gives you nice test support facilities.

But how to test beans which using special scopes like session or request?

The AbstractTestNGSpringContextTests does not provide support to test scoped beans.

Our test module provides a SimpleMapScope implementation, which can be used for scoped beans. There is also a spring configuration for the scopes request and session: session-request-testscopes.xml which can be used as a ContextConfiguration location.

For example you can write follow simple test case:


....

@ContextConfiguration(locations = {"/org/waffel/test/session-request-testscopes.xml",
  "/org/waffel/my-app-beans.xml})
public class SimpleScopeBeansTest extends AbstractTestNGSpringContextTests {

  /**
   * A bean which is in scope session.
   */
  @Autowired
  @Qualifier("sessionScopedBean")
  private MyBean sessionScopedBean;

  @Test
  public void testAccessToBean() {
    AssertNotNull(sessionScopedBean);
  }

....

This test uses the test scope spring configuration and another spring configuration, where the sessionScopedBean is in scope session. With the autowired feature, you have instantly access to the bean. Also if the bean is in session or request scope.

The SimpleMapScope implementation:


package org.waffel.test.spring;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

/**
 * This simple scope implementation uses internal a {@link Map} to hold objects
 * in the scope. This scope implementation can be used for testing beans which
 * wants to be stayed for example in session or request scope.
 * <p>
 * To use this scope in your test cases, simple configure a
 * {@link org.springframework.beans.factory.config.CustomScopeConfigurer} with
 * the required scope name:
 *
 * <pre>
 * &lt;bean class=&quot;org.springframework.beans.factory.config.CustomScopeConfigurer&quot;&gt;
 *   &lt;property name=&quot;scopes&quot;&gt;
 *     &lt;map&gt;
 *       &lt;entry key=&quot;session&quot;&gt;
 *         &lt;bean class=&quot;com.siemens.spice.dc.spring.SessionScope&quot; /&gt;
 *       &lt;/entry&gt;
 *     &lt;/map&gt;
 *   &lt;/property&gt;
 * &lt;/bean&gt;
 * </pre>
 *
 * Because the
 * {@link org.springframework.beans.factory.config.CustomScopeConfigurer} is a
 * {@link org.springframework.beans.factory.config.BeanPostProcessor} all
 * requested beans for the scope loaded with that post processor if the
 * registered scope match.
 * </p>
 *
 * @author waffel
 */
public class SimpleMapScope implements Scope {

  /**
   * This map contains for each bean name or ID the created object. The objects
   * are created with a spring object factory.
   */
  private final Map<string , Object> objectMap = new HashMap</string><string , Object>();

  /**
   * {@inheritDoc}
   */
  public Object get(final String theName, final ObjectFactory theObjectFactory) {
    Object object = objectMap.get(theName);
    if (null == object) {
      object = theObjectFactory.getObject();
      objectMap.put(theName, object);
    }
    return object;
  }

  /**
   * {@inheritDoc}
   */
  public String getConversationId() {
    return null;
  }

  /**
   * {@inheritDoc}
   */
  public void registerDestructionCallback(final String theName, final Runnable theCallback) {
    // nothing to do ... this is optional and not required
  }

  /**
   * {@inheritDoc}
   */
  public Object remove(final String theName) {
    return objectMap.remove(theName);
  }

}

The session-request-testscopes.xml source:


< ?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

  <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
      <map>
        <entry key="session">
          <bean class="org.waffel.test.spring.SimpleMapScope" />
        </entry>
        <entry key="request">
          <bean class="org.waffel.test.spring.SimpleMapScope" />
        </entry>
      </map>
    </property>
  </bean>

</beans>

Another approach can be found in ahöhma’s weblog.

Posted in spring Tagged: java, request, scope, session, singleton, spring, test, TestNG, unit

Syndicated 2009-04-27 11:45:59 from waffel's Weblog

Article about Buzztard (Part one)


Dave Phillips wrotes a very nice article about one of may open source projects: buzztard.

I hope in the next month’s there is more time for me to work on buzztard. As you know I write mostly testcases and discuss with other developers about the software design.

Posted in software Tagged: buzztard, C, gnome, music, tracker

Syndicated 2009-02-20 18:14:39 from waffel's Weblog

how to use EL from java in a JSF 1.2 environment


There are not much examples, how to use a ELExpression from your java code. The most examples I found, are focussing on “implement your own ELResolver”. The best documentation comes from SUN in form of tutorials and package/javadoc.

Now I will provide some tips how to deal with EL expressions from java. I have tested and implemented this in a JSF 1.2 web application, where I have access to the FacesContext.

In JSF 1.2 you have access to expression factory:


// get application from faces context
Application app = FacesContext.getInstance().getApplication();
ExpressionFactory exprFactory = app.getExpressionFactory();

Now you can use the expression factory to get a MethodExpression or ValueExpression. In my projects we need very often ValueExpressions.

But first you need also an ELContext. There are many implementations available of such context (for JSP, Faces and so on) and enough documentation how to create your own context.
You can access such context again from the faces context:


// getting the ELContext from faces context
ELContext elContext = FacesContext.getInstance().getELContext();
// creating value expression with the help of the expression factory and the ELContext
ValueExpression valExpr = exprFactory.createValueExpression(elContext, "#{devBean.devMode}", Boolean.class);

In this example I will use the boolean value from a “devBean” to work later with this value. Of course, you can inject the value expression, required class type and so on.
The last needed thing is to assign the value to a local variable:


Boolean developmentMode = (Boolean) valExpr.getValue(elContext);

Thats it!

Posted in java, JSF, software   Tagged: EL, ELContext, JSF, JSF1.2   

Syndicated 2008-11-28 19:47:09 from waffel's Weblog

updating mediawiki is easy


I have updated some homepages to the brand new mediawiki version 1.13.2 which was very easy. They have a very good description what you have to do, if you update to a new version and a very nice update script which works also for very old wiki versions (I have tested this with the 1.4.5 version).

But there ara small problems with own skin (for example on http://www.buzztard.org). The skin have to be fixed per hand. Hopfully ensonic can do this the next days.

Posted in administration, software   Tagged: mediawiki, upgrade   

Syndicated 2008-11-13 12:33:10 from waffel's Weblog

fun with h:dataTable and a4j:form


I have some facelet components and want to use them in a h:dataTable. My components containing some form elements like h:inputText, command buttons and so on. To avoid scrolling, I have placed them into a a4j:form.

Now in my h:dataTable loop I call these facelet components and want to have a list of inputText components for example. But every time, I typed in something, only the last input field called correct my setValue() method. All other input components dosn’t call the setter.

Here a very small example to imagine the problem:

The datatable


<h:dataTable value="myBackingBean.list" var="currentItem">
  <h:column>
    <waffel:input item="#{currentItem}"/>
  </h:column>
</h:dataTable>

The facelet component:


  ...
  <a4j:form>
    <h:inputText size="30" value="#{item.value}"/>
    <a4j:commandButton value="ok" action="#{item.applyValue}"/>
  </a4j:form>
  ...

To get this to work you have to place a a4j:region around the a4j:form!


  ...
  <a4j:region>
    <a4j:form>
      <h:inputText size="30" value="#{item.value}"/>
      <a4j:commandButton value="ok" action="#{item.applyValue}"/>
    </a4j:form>
  </a4j:region>
  ...

Now it works fine.

Posted in JSF   Tagged: a4j, dataTable, Facelets, JSF   

Syndicated 2008-10-07 09:41:05 from waffel's Weblog

expanding richfaces tree on datamodel changes


Sometimes you will select a tree node in a richfaces tree, triggered by your datamodel. There are several hints how to do this with a tree state advisor, but I have found another way to do this.

My main problem was, that I do not have a relation between my datamodel and the richfaces UITree components (nodes). This problem was introduced because I use the recursiveTreeAdaptor. I have not found a way to get a TreeRowData object from the UITree for my datamodel object.

I have searched in the richfaces implementation, if there is another way to work with my datamodel which have to expand the tree, if the datamodel is changed.

Lets clearify what I want to do: I have a datamodel with some root nodes and “normal” nodes in a tree like structure. I have also (in my TreeManager) a parameter which holds a selectedNode. A node can selected from the UI (the user clicks on a tree node and causes a node selection event) or from my datamodel, which calls a method in the TreeManager to select a specific tree node.

The tree manager contains a method to select a specific node like this:


public void select(final Node nextStepNode) {
  this.selectedNode = nextStepNode;

}

To expand the tree to the selected node, I have changed to select method:


public void select(final Node nextStepNode) {
  this.selectedNode = nextStepNode;
  try {
      // walk over the tree which expands the tree and uses a complete tree
      // range
      tree.walk(FacesContext.getCurrentInstance(), expandingDataVisitor, new CompleteTreeRange(), null, null);
    } catch (final IOException e) {
      if (LOG.isErrorEnabled()) {
        LOG.error(String.format("problem %s", e.getMessage()));
      }
    }
}

The tree walk method walks over the tree using my own data visitor and tree range. The tree range implementation tolds the tree to walk also over hidden nodes. You remember? The tree should expand all nodes to the selected node, also if the selected node is hidden.

The tree range implementation looks like:


public class CompleteTreeRange implements TreeRange {

  /**
   * {@inheritDoc}
   */
  @SuppressWarnings("unchecked")
  public boolean processChildren(final TreeRowKey rowKey) {
    return true;
  }

  /**
   * {@inheritDoc}
   */
  @SuppressWarnings("unchecked")
  public boolean processNode(final TreeRowKey rowKey) {
    return true;
  }

Now comes the hard stuff on my solution, the expandingDataVisitor:


public class ExpandingDataVisitor implements DataVisitor {
  public void process(final FacesContext theContext, final Object theRowKey, final Object theArgument)
      throws IOException {
    if (selectedNode.equals(tree.getRowData(theRowKey))) {
      tree.queueNodeExpand((TreeRowKey) tree.getParentRowKey(theRowKey));
    }
}

You can queue node expanding with a tree rowKey to the node, which you want to expand. You don’t need to queue all nodes on the path. The queueNodeExpand method works fine with one rowkey. The row describes itself the complete path to the node. If you use standard jsf ID’s, a possible treeRowKey looks like “jsp123:jsp124:jsp125″ wich is the complete path to your node (row key).

You have to know, that you don’t want expand the selected node (this is in most cases a leafe). You want to expand the tree to the parent of the selected node.

Syndicated 2008-09-09 12:19:13 from waffel's Weblog

Reuse facelets xhtml files and taglibs from jar archives


I have asked myself, if it is possible to use facelets xhtml files and taglibs from a jar file instead from the whole web application.

The short anwser: Yes, it is possible ;-)

The facelets documentation gives a hint how to use the tag lib from a jar file. But you cannot found in the documentation, if it is possible also to use a xhtml file (referenced from the taglib for example). Of course facelets uses the same approach to load xhtml files from a jar file as for the tag library.

Example:
The follow tag lib definition is placed in my JAR project under /META-INF/myProject.taglib.xml


<?xml version="1.0"?>
<!DOCTYPE facelet-taglib PUBLIC
  "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
  "http://java.sun.com/dtd/facelet-taglib_1_0.dtd">

<facelet-taglib>

    <namespace>http://thomaswabner.wordpress.com/waffel</namespace>

    <tag>
        <tag-name>select</tag-name>
        <source>components/select.xhtml</source>
    </tag>

</facelet-taglib>

The select.xhtml file is placed in the same project under /META-INF/components/select.xhml and contains some facelets definitions (ui component with a selectbox fo example). The point is, that facelets searches the jar archive under the /META-INF directory for the xhtml file.

Now you can simple use the tag in you web application. You only need to include the jar file with the tag library and xhtml file in you web application classpath.


<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns="http://www.w3.org/1999/xhtml"
          xmlns:ui="http://java.sun.com/jsf/facelets"
          xmlns:waffel="http://thomaswabner.wordpress.com/waffel"
          version="2.0">
  <ui:component>
     <waffel:select/>
  </ui:component>
</jsp:root>

Syndicated 2008-06-25 14:47:15 from waffel's Weblog

Disable live site with apache rewrite rules


Any times I have to work on a live site like http://www.capella-fidicinia.de or http://www.cryo-tekk.de. All these sites are Joomla instances and Joomla doe’s not allow to disbale the site complete. You can only put the site “offline” with a setting in the administration module. After putting such site into the offline mode, nobody can anymore change the content and the user got a inforation bar on the site.

But often I will change complete the layout (testing new skin, working on the existing skin and so on). But the user should not see my changes because it is very ugly if you browse to a side and with every click the layout changes.

My Joomla instances running behind a apache2 webserver as a virtual host. To put the site complete offline and inform the user about maintainance you can put the follow into you virtual host configuration:


RewriteEngine On
RewriteCond %{REMOTE_ADDR} !^194.136.37.140$
RewriteRule .* /var/www/domains/www.cryo-tekk.de/htdocs/maintainance.html [L]

With such entry only the IP adress 194.136.37.140 can see the site. All other IP adresses, which try to access the site are foreward to the maintainance.html site.

For more information about rewrite rules you can have a look here.

Syndicated 2008-06-19 10:52:28 from waffel's Weblog

getting node data from rich tree on user selection


I have had the problem to get node data from a richfaces tree, if the user selects a node. I have used a recursive tree adapter:


<rich:tree switchType="server"
           stateAdvisor="#{treeStateAdvisor}"
           nodeSelectListener="#{treeMgrt.onSelect}">

   <rich:recursiveTreeNodesAdaptor roots="#{treeMgrt.roots}" var="item" nodes=" {item.nodes}">

     <rich:treeNode>
         <h:outputText value="#{item}"/>
     </rich:treeNode> 

  </rich:recursiveTreeNodesAdaptor>
</rich:tree>  

The method in my tree manager onSelect(…) looks like this:


public void onSelect(final NodeSelectedEvent event) {
  final UITree theTree = this.getTree(event);
  if (null == theTree) {
    return;
  }
  final Object rowKey = theTree.getRowKey();
  // this works better
  final Object rowData = theTree.getRowData(rowKey);
  if (rowData instanceof ProductNode) {
    this.selectedNode = (ProductNode) rowData;
  }
}

Normally you can use theTree.getTreeNode(); but with a recursive tree model which method returns alway null. Instead of this I have used the getRowData() method which works for me.
I have filed a bug for richfaces. Hope the problem becomes shortly a solution.

Syndicated 2008-06-13 13:33:13 from waffel's Weblog

place a div element always bottom


A while ago I have searched for a solution to place a <div> element inside another <div> element always bottom. There are many solutions to put the div bottom from the whole html site but rar solutions to put it in the container div bottom.

Now here comes my solution …

I have one div container (calling it simple container) with a height of 100% (this container itself is placed for example in another parent container which has a height of 400px). And I have my div which should placed bottom of the container:


<div id="container" style="height:100%; position:relative;">
  <div id="bottom_div" style="height:10%; position:absolute; bottom:0px;"/>
</div>

The trick is to give the container div a position relative and then you can use the position absolute in the bottom div element. If the container div has no position style atribute it will not work.

Syndicated 2008-06-10 09:35:26 from waffel's Weblog

9 older entries...

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!