Highlight Selected Menu For Current Page Using SiteMesh

30 05 2008

In my previous post, Dynamically Load Menus with SiteMesh, I described how to load menus dynamically based on the variable in the pages. Here, to highlight last selected menu (which means current menu item) we can use same thing.

This time the variables we specify in every page will be name for the menu items.
And instead of include jsp page in the previous post, we need to set menu items like this :

<li>  
   <a class="${currentMenu == 'abc_menu' ? 'selected':''}"      
       title="Abc" href="abc.html">Abc</a>
</li>

Here, for every menu item, it is needed to specify class decision. And do not forget to add css style for selected.





Dynamically Load Menus with SiteMesh

30 05 2008

If you want to load different menus based on the current page using SiteMesh, you are on the right blog entry:)

In your template page, get decorator property and set it to currentMenu variable.

<c:set var="currentMenu" scope="request">
    <decorator:getProperty property="meta.menu"/>
</c:set>

and use it to include menu as menu page name

<jsp:include page="/includes/${currentMenu}.jsp"/>

and in your jsp pages, specfiy which menu to be used when this page is loaded

<meta name="menu" content="abc_menu"/>

Here, be careful with the names. As in the last code, you stated your menu name abc_menu. Then you need a jsp page for menu : abc_menu.jsp. You may only just menu items.

If you state in another jsp page something like this :

<meta name="menu" content="abc_menu2"/>

then you will need abc_menu2.jsp

That is it.





Ext Js HowTo : Change A Div’s Content

29 05 2008

To change the content of a div element, you can use update(..) method of the Element. And to find the div element you can use Ext.fly(…).
Here is a working sample

change.js

Ext.onReady(function() {
 Ext.get('mylink').on('click', function(){
     Ext.fly('area').update('This is added content');
 });
});

In test.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="./ext/resources/css/ext-all.css" />
<link id="theme" rel="stylesheet" type="text/css" href="./css/empty.css" />
<link rel="shortcut icon" href="./img/extjs.ico" />
<script type="text/javascript" src="./ext/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="./ext/ext-all-debug.js"></script>
<script type="text/javascript" src="js/change.js"></script>
<title id="page-title">Click</title>
</head>

<body>
 <a id="mylink">ChangeContent</a>
 <br/>
 <div id="area">empty</div>
</body>

When you click the ChangeContent link, empty will be replaced by This is added content text.





Unit Testing Repositories with DbUnit and Spring

28 05 2008
In this post, I will create a base class for repository tests. I used DBUnit to populate database configured in a testContext.xml. And I used Spring test annotations to wire test classes with dataSource and repositories.
Requirements
* Spring 2.5
* DbUnit 2.2.2
* Junit 4.4Here you are

import javax.sql.DataSource;

import org.dbunit.DataSourceDatabaseTester;
import org.dbunit.IDatabaseTester;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:*testContext.xml" })
@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class })

public abstract class AbstractRepositoryTest {

 private IDatabaseTester databaseTester;

 private DataSource dataSource;

 @Autowired
 public void setDataSource(DataSource dataSource) {
     this.dataSource = dataSource;
 }

 @Before
 public void setUpDatabase() throws Exception {
    try {
      databaseTester = new DataSourceDatabaseTester(dataSource);
      databaseTester.setTearDownOperation(DatabaseOperation.DELETE_ALL);
      IDataSet dataSet = getDataSet();
      databaseTester.setDataSet(dataSet);

      databaseTester.onSetup();
  } catch (Exception e) {
     e.printStackTrace();
     throw e;
  } } protected abstract IDataSet getDataSet() throws DataSetException ; @After public void tearDownDatabase() throws Exception { if (databaseTester != null) { databaseTester.onTearDown(); } } }

And here is a saimple example test for MyRepository.

import java.util.List;

import javax.sql.DataSource;

import org.dbunit.DataSourceDatabaseTester;
import org.dbunit.IDatabaseTester;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.csv.CsvURLDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.junit.After;import org.junit.Assert;
import org.junit.Before;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;

public class MyRepositoryTest extends AbstractRepositoryTest {

 private MyRepository myRepository;

 @Autowired
 public void setMyRepository(@Qualifier("myRepository") MyRepository myRepository) {
      this.myRepository = myRepository;
 }

 protected IDataSet getDataSet() throws DataSetException {
    // returns CVS files in the currenct directory
    return new CsvURLDataSet(getClass().getResource(""));
}

 @Test
 public void listMyXEntities() {
    List xList = myRepository.listXEntities();
    Assert.assertEquals(3, xList.size());
  }
}

I really like the simplicity that comes with annotations!

PS : In the AbstractRepositoryTest’s setUpDatabase() method, there is a try-catch. I added it because in  org.springframework.test.context.junit4.SpringMethodRoadie.java (v1.13), at line 335, there is a catch like :

catch (FailedBefore ex) {
}
So in case of any exception in set up, you loose it.




Ext JS Tip : How To Make ComboBox Send Value Field.

19 05 2008

When you use Ext JS’s ComboBox, if you don’t set hidden name or id, it send display field value, not value field. To handle this, it has to be set. Be careful about uniqueness of the hidden name, for more details you can check Ext JS ComboBox’s documantation

var unitField = new Ext.form.ComboBox({   
    id:'unitField',   
    name: 'unit',   
    fieldLabel: 'Unit',   
    store:unitStore,   
    mode: 'remote',   
    displayField: 'name',   
    valueField: 'id',   
    hiddenName : 'unitId',   
    allowBlank: false,   
    anchor:'95%',   
    triggerAction: 'all'
});




How to Populate Ext JS ComboBox using Spring Controller

15 05 2008

To populate Ext JA ComboBox using Spring Controller, you can create an Ajax request using Ext.data.HttpProxy and as response you can return Json Objects. And using JsonReader, you can read values and pupolate ComboBox.

Requirements
* Spring
* ExtJS 2.0
* json-lib
* spring-json

Here is class of the combobox’s item :

public class Unit { private long id private String name;

 public Unit(long id, String name){
     this.id = id;   this.name = name;
 }

 public String getName() {
     return name;
 }

 private void setName(String name) {
    this.name = name;
 }

 public long getId() {
   return id;
 }

 private void setId(long id) {
    this.id = id;
 }
}

Here is the controller. It is multiaction controller. But it does not have to be so. The request is mapped to loadUnits() method, which retrieves units from a source (here it is a method, it can be a repository), and returns a JSonView as a view.

import java.util.ArrayList;import java.util.List;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.JsonView;

@Controller
public class MyMultiController {

 @RequestMapping("/getunits.do")
 public ModelAndView loadUnits() {
    //Somehow get units.
    List units = getUnits();
    return new ModelAndView(new JsonView(), "units", units);
 }

 private List getUnits() {
    List units =  new ArrayList();
    units.add(new Unit(1, "Unit 1"));
    units.add(new Unit(2, "Unit 2"));
    return units;
 }
}

Here is the ExtJs Code for ComboBox. It creates Ext.data.HttpProxy, which is an implementation of Ext.data.DataProxy that reads a data object from an Ext.data.Connection object configured to reference a certain URL. It gets data from getsunits.do url. And mode od the unit combobox is set to remote.

var unitStore = new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
        url: 'getunits.do'
    }),
    reader: new Ext.data.JsonReader({
           root:'units'
         },
         [{name: 'id', mapping:'id'}, {name: 'name' , mapping:'name'}])
});

 var unitField = new Ext.form.ComboBox({
      id:'unitField',
      name: 'unit',
      fieldLabel: 'Unit',
      store:unitStore,
      mode: 'remote',
      displayField: 'name',
      allowBlank: false,
      valueField: 'id',
      hiddenName : 'unitId',
      anchor:'95%',
      triggerAction: 'all'
 });

When you put the unitField in a form, then it will be populated when the user clicks the combobox.
I hope it is helpful.








Follow

Get every new post delivered to your Inbox.