Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
Clear All
new posts

    IBATIS/SPRING GWT-RPC DataSource implementation

    I thought I share my eclipse project here that shows a master detail screen for a table in a MS Sql database including filtering, paging and sorting via ibatis and spring.
    The whole stacktrace would be;
    Custom Widget = The widget that shows a grid and a tab panel with the fields for editing
    EditWidget = The base widget that shows the grid and fields from the datasource
    DataSource = the GWT-RPC Datasource implementation (http://forums.smartclient.com/showth...tRpcDataSource)
    The GWT RPC methodes (Get, Update and Remove)
    The Spring config files
    The ibator config file
    The custom query for paging and sorting

    The goal is to CRUD the data in a large table and have tabs for related data to show after a master row is selected in the grid.

    I started with the GWT eclipse wizard that generates a project with source folders for client, server and shared. The ibator POJO's go into the shared folder.

    Here are the steps;
    1) Create the table
    Code:
    CREATE TABLE [dbo].[OEM](
    	[OemCode] [varchar](15) NOT NULL,
    	[Name] [nvarchar](50) NULL,
    	[Address] [nvarchar](120) NULL
    2) Create the ibatis code using the ibator plugin
    Code:
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE ibatorConfiguration PUBLIC "-//Apache Software Foundation//DTD Apache iBATIS Ibator Configuration 1.0//EN" "http://ibatis.apache.org/dtd/ibator-config_1_0.dtd" >
    <ibatorConfiguration>
    	<classPathEntry location="sqljdbc.jar" />
    	<ibatorContext id="context1">
    		<commentGenerator type="PlaneCommentGenerator">
    			<property name="suppressDate" value="true"/>
    		</commentGenerator>
    		<jdbcConnection driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver"
    			connectionURL="jdbc:sqlserver://172.16.1.65:1433;DatabaseName=esos;SelectMethod=cursor;"
    			userId="assessor" password="------" />
    
    		<javaModelGenerator targetPackage="esos.shared.data.ibatisPOJO" 
    			targetProject="Esos" />
    		<sqlMapGenerator targetPackage="esos.sqlmaps"
    			targetProject="Esos" />
    		<daoGenerator type="SPRING" targetPackage="esos.server.DAO"
    			targetProject="Esos" />
    
    		<table tableName="OEM" 
    				enableCountByExample="false" enableDeleteByExample="false" 
    				enableSelectByExample="false" enableUpdateByExample="false">
    			<property name="useActualColumnNames" value="true"/>
    		</table>
    		
    	</ibatorContext>
    </ibatorConfiguration>
    3) Create the queries for paging, filtering and sorting
    Code:
      	<sql id="where_clause">
      	  <dynamic prepend="WHERE">
    	      <isNotNull prepend="AND" property="oemCode">
    	      	 OemCode like #oemCode:VARCHAR#
    	      </isNotNull>
    	      <isNotNull prepend="AND" property="name">
    	      	 Name like #name:VARCHAR#
    	      </isNotNull>
          </dynamic>
      	</sql>
      	
       <select id="selectTotalRows" parameterClass="esos.shared.data.ibatisPOJO.Oem" resultClass="int">
    		SELECT count(*) FROM OEM
    		<include refid="where_clause" /> 
    	</select>
    	
    	<select id="selectByFilter" parameterClass="esos.shared.data.ibatisPOJO.Oem" resultClass="esos.shared.data.ibatisPOJO.Oem">
    	SELECT * FROM (select
    		 <isNotNull property="paging.endRow"> top $paging.endRow$ ROW_NUMBER() OVER(
    			Order by <isNull property="paging.sortBy">Name DESC</isNull> 
    				     <isNotNull property="paging.sortBy">$paging.sortBy$ $paging.sortorder$</isNotNull>) as Row,
    		 </isNotNull>
    		 
        	 OemCode, Name, Address
     	   FROM OEM
     	<include refid="where_clause" /> 
          
          
           ) as page
    	    <isNotNull property="paging.endRow"> WHERE  Row &gt;= #paging.startRow# AND Row &lt;= #paging.endRow# </isNotNull> 
    		ORDER BY <isNull property="paging.sortBy">Name DESC</isNull> 
    				 <isNotNull property="paging.sortBy">$paging.sortBy$  $paging.sortorder$</isNotNull> 
    				 
      </select>
    4) Write the custom DAO implementation
    Code:
    @SuppressWarnings("unchecked")
    	public PagingList<Oem> selectByFilter(Oem filter, Paging paging) {
    		PagingList<Oem> Oems = new PagingList<Oem>();
    		if (paging!=null){
    			filter.setPaging(paging);
    			if (filter.getOemCode() !=null){
    				filter.setOemCode("%" + filter.getOemCode() + "%");
    			}
    			if (filter.getName() !=null){
    				filter.setName("%" + filter.getName() + "%");
    			}
    			Oems.setTotalRows((Integer)  getSqlMapClientTemplate().queryForObject("OEM.selectTotalRows", filter));
    		}else{
    			filter.setPaging(new Paging());
    		}
    		Oems.addAll(getSqlMapClientTemplate().queryForList("OEM.selectByFilter", filter));
    		return Oems;
    	}
    5)Configure SPRING (startup by servlet in web.xml)
    Code:
    <listener>
            <listener-class>
                org.springframework.web.context.ContextLoaderListener
            </listener-class>
        </listener>
    
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring.xml</param-value>
        </context-param>
    Spring.xml (db username and password in config.properties):
    Code:
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
           
    	<bean id="propertyConfigurer"
    		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    		<property name="location" value="WEB-INF/config.properties" />
    	</bean>
    	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    		<property name="driverClassName" value="${database_driver}" />
    		<property name="url" value="${database_url}" />
    		<property name="username" value="${database_user}" />
    		<property name="password" value="${database_password}" />
    		<property name="defaultAutoCommit" value="true"/>
    		<property name="defaultTransactionIsolation" value="2"/>
    		<property name="maxActive" value="10"/>
    		<property name="removeAbandoned" value="true"/>
    		<property name="removeAbandonedTimeout" value="30"/>
    		<property name="logAbandoned" value="false"/>
    		<property name="validationQuery" value="select top 1 DealerCode from Dealer"/>
    	</bean>
    	
    
        <bean id="transactionManager" 
              class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>
         <aop:config>
            <aop:advisor pointcut="execution(* esos.server.DAO.*DAOImpl.*(..))" advice-ref="txAdvice"/>
        </aop:config>
        <tx:advice id="txAdvice">
            <tx:attributes>
            	
                <tx:method name="update*" timeout="600"/>
                <tx:method name="exec*" timeout="1800"/>
    			<tx:method name="*" propagation="NEVER" timeout="60"/>
            </tx:attributes>
        </tx:advice>  
        
    	
    	<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
    		<property name="configLocation">
    			<value>classpath:esos/sqlmaps/sql-map-config.xml</value>
    		</property>
    		<property name="useTransactionAwareDataSource">
    			<value>true</value>
    		</property>
    		<property name="dataSource">
    			<ref bean="dataSource" />
    		</property>
    	</bean>
    
    
    	
    	
    	
    	<bean id="oemDAO" class="esos.server.DAO.OemDAOImpl">
    		<property name="sqlMapClient">
    			<ref bean="sqlMapClient" />
    		</property>
    	</bean> 
    	
    	
    
    </beans>
    6) GWT-RPC implementation
    get the spring context
    Code:
    context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    and perform the GWT-RPD actions through Ibatis
    Code:
     public PagingList<Oem> get(Oem filter, Paging paging) throws BackendException {
        try {
          OemDAO oemDAO=(OemDAO) context.getBean("oemDAO");
          return oemDAO.selectByFilter(filter, paging);
        }catch (Throwable t) {
          t.printStackTrace();
          throw new BackendException(t);
        }
      }
    
      public Oem update(Oem record) throws BackendException {
        try {
          OemDAO oemDAO=(OemDAO) context.getBean("oemDAO");
          Oem oldRecord= oemDAO.selectByPrimaryKey(record.getOemCode());
          if (oldRecord==null){
            oemDAO.insert(record);
          }else{
    		oemDAO.updateByPrimaryKey(record);
          }
          return record;
        }catch (Throwable t) {
          t.printStackTrace();
          throw new BackendException(t);
        }
      }
    
      public String remove(String primaryKey) throws BackendException {
        try {
          OemDAO oemDAO=(OemDAO) context.getBean("oemDAO");
          oemDAO.deleteByPrimaryKey(primaryKey);
          return null;
        }catch (Throwable t) {
          t.printStackTrace();
          throw new BackendException(t);
          }
      }
    7) The GWT-RPC datasource
    Code:
    package esos.client.datasource;
    
    
    import java.util.HashMap;
    import java.util.Map;
    
    import com.google.gwt.core.client.GWT;
    import com.google.gwt.user.client.rpc.AsyncCallback;
    import com.smartgwt.client.core.DataClass;
    import com.smartgwt.client.data.DSRequest;
    import com.smartgwt.client.data.DSResponse;
    import com.smartgwt.client.data.DataSourceField;
    import com.smartgwt.client.data.fields.*;
    import com.smartgwt.client.rpc.RPCResponse;
    import com.smartgwt.client.widgets.grid.ListGridRecord;
    import esos.client.data.ibatisPOJO.Paging;
    import esos.client.lib.GwtRpcDataSource;
    import esos.client.remoteservice.OemService;
    import esos.client.remoteservice.OemServiceAsync;
    import esos.client.widget.dialog.ErrorDialog;
    import esos.shared.PagingList;
    import esos.shared.data.ibatisPOJO.Oem;
    
    
    
    public class OemDS extends GwtRpcDataSource {
    
        private static OemDS instance = null;
        
        public Oem filter =  new Oem();
       
        private final OemServiceAsync oemService = GWT.create(OemService.class);
        
        public static OemDS getInstance(Oem filter) {
            if (instance == null) {
                instance = new OemDS();
            }
            instance.filter = filter;
            return instance;
        }
    
        public OemDS() {
        	DataSourceField field;
            field = new DataSourceTextField("oemCode");
            field.setPrimaryKey (true);
            field.setRequired (true);
            addField (field);
            
            field = new DataSourceTextField ("name");
            field.setRequired (true);
            addField (field);
     
            field = new DataSourceTextField ("address");
            field.setCanFilter(false);
            addField (field);
        }
    
    	
    
    	@Override
    	protected void executeFetch(final String requestId, final DSRequest request, final DSResponse response) {
    		//TODO request.getSortBy has a issue in smartgwt
    		//http://code.google.com/p/smartgwt/issues/detail?id=389		
    		//Paging paging=new Paging(request.getStartRow (),request.getEndRow (),request.getSortBy () );
    		Paging paging=new Paging(request.getStartRow (),request.getEndRow (),request.getAttribute("sortBy") );
    		
    		copyValues(request.getCriteria(),filter);
    		oemService.get(filter, paging, new AsyncCallback<PagingList<Oem>>() {
    
    			public void onFailure(Throwable caught) {
    				ErrorDialog.showErrorDialog( caught);
    		        response.setStatus (RPCResponse.STATUS_FAILURE);
    		        processResponse (requestId, response);
    				
    			}
    
    			public void onSuccess(PagingList<Oem> result) {
    				if (result.getTotalRows()>result.size()){
    		    		response.setTotalRows (result.getTotalRows());
    		    	}
    		        ListGridRecord[] list = new ListGridRecord[result.size()];
    		        for (int i = 0; i < list.length; i++) {
    		            ListGridRecord record = new ListGridRecord ();
    		            copyValues (result.get(i), record);
    		            list[i] = record;
    		        }
    		        response.setData (list);
    		        processResponse (requestId, response);
    			}
    		});
    		
    		
    	}
    
    	@Override
    	protected void executeAdd(final String requestId, final DSRequest request, final DSResponse response) {
    		update(requestId, request, response);
    	}
    	
    	@Override
    	protected void executeUpdate(final String requestId, final DSRequest request, final	DSResponse response) {
    		update(requestId, request, response);
    	}
    	
    	private void update(final String requestId, final DSRequest request, final	DSResponse response){
    		 // Retrieve record which should be added or updated.
    		Oem record = new Oem ();
            copyValues (new ListGridRecord (request.getData ()), record);
            
            oemService.update(record,new AsyncCallback<Oem>() {
                public void onFailure (Throwable caught) {
                	ErrorDialog.showErrorDialog(  caught);
                    //response.setStatus (RPCResponse.STATUS_FAILURE);
                	response.setStatus(RPCResponse.STATUS_VALIDATION_ERROR);
                	Map<String,String> errors = new HashMap<String,String>();
                	errors.put("oemCode", caught.getMessage());
                    processResponse (requestId, response);
                }
                public void onSuccess (Oem result) {
                    ListGridRecord[] list = new ListGridRecord[1];
                    ListGridRecord newRec = new ListGridRecord ();
                    copyValues (result, newRec);
                    list[0] = newRec;
                    response.setData (list);
                    processResponse (requestId, response);
                }
            });
    	}
    	
    	@Override
    	protected void executeRemove(final String requestId, final DSRequest request, final DSResponse response) {
    		// Retrieve record which should be deleted.
            final ListGridRecord rec = new ListGridRecord (request.getData ());
            String primaryKey = rec.getAttributeAsString("oemCode");
            oemService.remove(primaryKey,new AsyncCallback<String>() {
                public void onFailure (Throwable caught) {
                	ErrorDialog.showErrorDialog(  caught);
                    response.setStatus (RPCResponse.STATUS_FAILURE);
                    processResponse (requestId, response);
                }
                public void onSuccess (String result) {
                    ListGridRecord[] list = new ListGridRecord[1];
                    // We do not receive removed record from server.
                    // Return record from request.
                    list[0] = rec;
                    response.setData (list);
                    processResponse (requestId, response);
                }
    
            });
    	}
    
    	public static void copyValues (DataClass from, Oem to) {
    		to.setOemCode(from.getAttributeAsString("oemCode"));
    		to.setName(from.getAttributeAsString("name"));
    		to.setAddress(from.getAttributeAsString("address"));
    		from.getAttributes();
        }
    
        private static void copyValues (Oem from, ListGridRecord to) {
        	to.setAttribute("oemCode", from.getOemCode());
        	to.setAttribute("name",from.getName());
        	to.setAttribute("address", from.getAddress());
        }
    
    	
    
    
    	
    }
    8) The base widget to edit/sort/filter a datasource
    Code:
    /**
     * EditWidget.java [Jul 19, 2007]
     * 
     * Copyright (c) ExiNet, (Pty) Ltd. All Rights Reserved.
     */
    package esos.client.widget;
    
    import com.google.gwt.user.client.Timer;
    import com.smartgwt.client.data.Criteria;
    import com.smartgwt.client.data.DSCallback;
    import com.smartgwt.client.data.DSRequest;
    import com.smartgwt.client.data.DSResponse;
    import com.smartgwt.client.data.SortSpecifier;
    import com.smartgwt.client.types.DragDataAction;
    import com.smartgwt.client.types.SortDirection;
    import com.smartgwt.client.widgets.IButton;
    import com.smartgwt.client.widgets.Label;
    import com.smartgwt.client.widgets.form.DynamicForm;
    import com.smartgwt.client.widgets.grid.ListGrid;
    import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
    import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
    import com.smartgwt.client.widgets.events.ClickEvent;  
    import com.smartgwt.client.widgets.events.ClickHandler;
    import com.smartgwt.client.widgets.layout.HLayout;
    import com.smartgwt.client.widgets.layout.VLayout;
    import com.smartgwt.client.widgets.tab.Tab;
    import com.smartgwt.client.widgets.tab.TabSet;
    import esos.client.controller.ClientController;
    import esos.client.data.ibatisPOJO.Paging;
    import esos.shared.data.system.Language;
    import esos.client.lib.GwtRpcDataSource;
    
    
    /**
     * This is an abstract class for editing an entity of any kind.  
     * Provides new/edit delete etc functionality so you can do the rest.
     * 
     * @author meindert 2009 
     */
    public abstract class EditWidget extends VLayout {
    	
    	protected final Language language = ClientController.getInstance().getLanguage();
    	
    	protected GwtRpcDataSource datasource;
    	private Paging paging=null;
    	
    
    	public DynamicForm filterForm;
    	public final ListGrid dataGrid = new ListGrid();
    	public final DynamicForm editForm = new DynamicForm();
    	public final HLayout dataGridButtonPanel = new HLayout();
    	public final TabSet editTabSet = new TabSet();
    	public final HLayout buttonPanel = new HLayout();
    	private Integer periodicRefreshing;
    	protected boolean dirty;
    	
    	protected String panelId;
    
    	protected Criteria filter;
    		
    	/**
    	 * Returns the name of the entity (eg "Dealer")
    	 * @return
    	 */
    	public abstract String getEntityName();
    	
    	/**
    	 * Returns the name of the entity (eg "Dealers")
    	 * @return
    	 */
    	public abstract String getEntityNamePlural();
    	
    	/**
    	 * Returns the field name of the primary key
    	 * The PK field is readonly for updates and editable for inserts
    	 * @return
    	 */
    	public abstract String getPrimaryKeyFieldName();
    	
    	/**
    	 * Executed when a record in the grid is selected
    	 */
    	public abstract void onRecordSelected(RecordClickEvent event);
    	
    	
    	/**
    	 * Constructs an EditWidget
    	 * @param datasource The datasource to use
    	 */
    	public EditWidget(GwtRpcDataSource datasource, String panelId) {
    		this.panelId=panelId;
    		this.datasource = datasource;
    	}
    	
    	public void initWidget() {		
    		setWidth100();
    		setHeight100();
    		setMembersMargin(10);
    		
    		//Heading
    		Label titleHeader = new Label();  
    		titleHeader.setHeight(10);  
    		titleHeader.setWidth100();  
    		titleHeader.setContents("<b>" + language.getListOfName()+" "+getEntityNamePlural() + "</b>");  
            
    		
    	      //Grid
    		dataGrid.setWidth100();  
    		dataGrid.setHeight("*"); 
    //		dataGrid.setPadding(0);
    //		dataGrid.setMinHeight(200); <=Doesn't work
    		dataGrid.setMargin(0);
    		dataGrid.setCanDragRecordsOut(true);  
    		dataGrid.setDragDataAction(DragDataAction.NONE);  
    		dataGrid.setAlternateRecordStyles(true);  
    		dataGrid.setAutoFetchData(true); 
    		dataGrid.setShowFilterEditor(true);
    		dataGrid.setFilterOnKeypress(false);
    		dataGrid.addRecordClickHandler(new RecordClickHandler() {  
    			public void onRecordClick(RecordClickEvent event) {
    				if (getPrimaryKeyFieldName()!=null){
    					editForm.getField(getPrimaryKeyFieldName()).setDisabled(true);
    			   	 }
    				editTabSet.selectTab(panelId + "_viewTab");
    				editForm.reset();  
                	editForm.editSelectedData(dataGrid);  
                	onRecordSelected(event);
    				
    			}  
            });  
    		dataGrid.setDataSource(datasource);
    		if (filter!=null){
    			dataGrid.setInitialCriteria(filter);
    		//	dataGrid.fetchData(filter);
    		}else{
    			//dataGrid.fetchData();
    		}
    		
    		IButton refreshButton = new IButton(language.getRefreshName()); 
    		refreshButton.addClickHandler(new ClickHandler() {  
                public void onClick(ClickEvent event) {
                	//dataGrid.invalidateCache();
                	refreshGrid();
                }  
            });  
    		dataGridButtonPanel.setHeight(10);
    		dataGridButtonPanel.setPadding(5);
    		dataGridButtonPanel.addMember(refreshButton);
    
    		
    		
    		
    		//Edit tabs
    		
    		editTabSet.setHeight(250);
            Tab viewTab = new Tab(getEntityName());  
            viewTab.setID(panelId + "_viewTab");
      
        	//editForm.setIsGroup(true);  
    		//editForm.setGroupTitle(getEntityName());  
            VLayout editCanvas= new VLayout();
            editForm.setWrapItemTitles(false);
    		editForm.setNumCols(4); 
    		editForm.setWidth(500);
    		editForm.setHeight100();
    		editForm.setDataSource(datasource);
    		editCanvas.addMember(editForm);
    		editCanvas.addMember(buttonPanel);
    		editCanvas.setHeight100();
            viewTab.setPane(editCanvas);  
            
      
            editTabSet.setTabs(viewTab);  
      
            //Button panel
           // Button newButton = new Button();
        	//Button editButton = new Button(language.getEditName()+" "+getEntityName());
        	//Button deleteButton = new Button(language.getDeleteName()+" "+getEntityName());
        	//Button cancelButton = new Button(language.getCancelChangesName());
        	//Button refreshButton = new Button(language.getRefreshName());
        	
        	 IButton saveButton;
        	 if (getPrimaryKeyFieldName()==null){
        		 saveButton = new IButton(language.getUpdateName()+" "+getEntityName()); 
        	 }else{
        		 saveButton = new IButton(language.getUpdateAddName()+" "+getEntityName());
        	 }
        	 saveButton.setID(panelId + "_saveButton");
        	 saveButton.addClickHandler(new ClickHandler() {  
                 public void onClick(ClickEvent event) {  
                	 saveForm();
                 }
             });
        	 
        	IButton newButton = new IButton(language.getNewName()+" "+getEntityName());  
        	newButton.addClickHandler(new ClickHandler() {  
                 public void onClick(ClickEvent event) { 
                	 editTabSet.selectTab("viewTab");
                	 if (getPrimaryKeyFieldName()!=null){
                		 editForm.getField(getPrimaryKeyFieldName()).setDisabled(false);
                	 }
                	 editForm.editNewRecord();
                	 dirty=true;
                 }  
             }); 
        	
        	 
        	 IButton deleteButton = new IButton(
        			 language.getDeleteName()+" "+getEntityName());  
        	 deleteButton.addClickHandler(new ClickHandler() {  
                 public void onClick(ClickEvent event) {  
                	 dataGrid.removeSelectedData();  
                 }  
             });  
             
             
    		buttonPanel.setPadding(5);
    		buttonPanel.setHeight(10);
    		buttonPanel.addMember(saveButton);
    		buttonPanel.addMember(newButton);
    		buttonPanel.addMember(deleteButton);
    		//buttonPanel.addMember(editButton);	
    		//buttonPanel.addMember(refreshButton);
    		//buttonPanel.setBorder("2px solid black");
    		
            //Render the layout
    		VLayout gridCanvas = new VLayout();
            if (filterForm!=null){
            	filterForm.setGroupTitle(language.getFilter() + " " + getEntityNamePlural());
            	filterForm.setIsGroup(true); 
            	filterForm.setPadding(5); 
            	gridCanvas.addMember(filterForm);  
            }else{
            	gridCanvas.addMember(titleHeader);
            }
            gridCanvas.addMember(dataGrid);
    		gridCanvas.addMember(dataGridButtonPanel);
     
    		
    		
            addMember(gridCanvas);  
            addMember(editTabSet);  
            //addMember(buttonPanel);  
            
           // draw(); 
            
            /*
    		 SectionStack sectionStack = new SectionStack();  
    	       // sectionStack.setBorder("2px dotted blue");  
    	        sectionStack.setWidth100();  
    	        sectionStack.setHeight100();  
    	        sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE);  
    	        sectionStack.setAnimateSections(true);  
    	        sectionStack.setOverflow(Overflow.HIDDEN);  
    	  
    	        SectionStackSection gridSection = new SectionStackSection();  
    	        gridSection.setTitle();  
    	        gridSection.setExpanded(true);  
    	        gridSection.setItems(dataGrid);  
    	  
    	        SectionStackSection detailsSection = new SectionStackSection();  
    	        detailsSection.setTitle(getEntityName());  
    	        detailsSection.setExpanded(true);  
    	        detailsSection.setItems(editTabSet);  
    	  
    	        sectionStack.setSections(gridSection, detailsSection);  
    	        sectionStack.draw();
    	        addChild(sectionStack);
    	        //sectionStack.draw(); 
    	  */      
    	        
    	/*	Layout mainHpanel = null;
    		if (!verticalLayout) {
    			mainHpanel = new HLayout();			
    			//((HorizontalPanel)mainHpanel).setBorderWidth(1);
    		} else {
    			mainHpanel = new VLayout();
    			//((VerticalPanel)mainHpanel).setBorderWidth(1);			
    			mainHpanel.setWidth(Window.getClientWidth()-50+"px");
    		}
    		mainHpanel.setBorder("2px solid blue");
    		mainHpanel.setHeight100();
    		VLayout leftPanel = new VLayout();
    		leftPanel.setBorder("2px solid red");
    		leftPanel.setPadding(15);
    
    		mainHpanel.addMember(leftPanel);
    		
    		Label label = new Label("<b>"+language.getListOfName()+" "+getEntityNamePlural()+"</b>");
    		label.setHeight(20);
    		
    		
    		
    		
    		dataGrid.setWidth100();  
    		dataGrid.setHeight(250);  
    		//dataGrid.setMargin(10);
    		dataGrid.setCanDragRecordsOut(true);  
    		dataGrid.setDragDataAction(DragDataAction.NONE);  
    		dataGrid.setAlternateRecordStyles(true);  
    		dataGrid.setAutoFetchData(true); 
    		dataGrid.setShowFilterEditor(true);
    		dataGrid.setFilterOnKeypress(false);
    		dataGrid.addRecordClickHandler(new RecordClickHandler() {  
    	            public void onRecordClick(RecordClickEvent event) {  
    	            	editForm.reset();  
    	            	editForm.editSelectedData(dataGrid);  
    	            }  
    	        });  
    		dataGrid.setDataSource(datasource);  
    		
    		
    		leftPanel.addMember(label);
    		if (filterForm!=null){
    			leftPanel.addMember(filterForm);
    		}
    		//buttonPanel = hPanel;
    		//Label lable = ;
    		//lable.setHeight(10);
    		
    		leftPanel.addMember(dataGrid);
    		//leftPanel.addMember(subSelectionPanel);
    		leftPanel.addMember(buttonPanel);
    		
    		//dataListBox.addItem(language.getLoadingMessage());
    				
    				
    		
    
    	//	dataListBox.setMultipleSelect(false);
    	//	dataListBox.setVisibleItemCount(5);
    		setPadding(5);
    		setBorder("2px solid pink");
    		
    		//leftPanel.setHorizontalAlignment(ALIGN_CENTER);
    		editCanvas = new VLayout();
    		editCanvas.setHeight100();
    		editCanvas.setBorder("2px solid yellow");
    		/*rightPanel = new VLayout();
    		rightPanel.addMember(detailHTML);
    		rightPanel.setBorder("2px solid green");
    		rightPanel.setPadding(15);
    		rightPanel.setWidth100();
    		
    		 
    		editForm.setIsGroup(true);  
    		editForm.setGroupTitle(getEntityName());  
    		editForm.setNumCols(4);  
    		editForm.setDataSource(datasource);  
            
            editCanvas.addMember(editForm);
            mainHpanel.addMember(editCanvas);
            
    		editCanvas.addChild(rightPanel);
    
    		
    		rightPanel.addMember(waitHTML);
    		rightPanel.addMember(form);
    		
    		//editControlPanel.setSpacing(5);
    		editControlPanel.addMember(saveButton);
    		editControlPanel.addMember(cancelButton);
    		//rightPanel.setBorderWidth(0);		
    		addMember(mainHpanel);
    		addMember(statusLine);*/
    	}
    	
       
    
    	
    	
    	private void periodicRefreshing() {
    		
    		new Timer() {
    			public void run() {
    				//dataGrid.invalidateCache();
    				//Only auto refresh when there is one page of date
    				if (paging!=null && paging.getOnePage()){
    					refreshGrid();
    				}
    				//Recurse the timer, cancel by setting the semaphore to null (or 0)
    				if (periodicRefreshing!=null && periodicRefreshing>0){
    					periodicRefreshing();
    				}
    			}
    		}.schedule(periodicRefreshing);
    	}
    
    	/**
    	 * Called to enable periodic reloading of the data 
    	 * 
    	 * @param periodicRefreshing the request Time interval in seconds (set to null or 0 to disable)
    	 */
    	public void enablePeriodicRefreshing(Integer periodicRefreshing) {
    		this.periodicRefreshing = (periodicRefreshing==null ? null : periodicRefreshing*1000);
    		if (periodicRefreshing!=null && periodicRefreshing>0){
    			periodicRefreshing();
    		}
    	}
    
    	/**
    	 * Called to enable reloading of the data every second 
    	 */
    	public void enablePeriodicRefreshing() {
    		enablePeriodicRefreshing(1);
    	}
    	/**
    	 * Called to disable reloading of the data every second 
    	 */
    	public void disablePeriodicRefreshing() {
    		enablePeriodicRefreshing(null);
    	}
    	
    	public Integer getPeriodicRefresrate() {
    		if (periodicRefreshing==null) return null;
    		return periodicRefreshing/1000;
    	}
    
    	public void setPanelId(String panelId) {
    		this.panelId = panelId;
    	}
    
    	public String getPanelId() {
    		return panelId;
    	}
    
    	public Paging getPaging() {
    		return paging;
    	}
    
    	public void setPaging(Paging paging) {
    		this.paging = paging;
    	}
    	
    	private void refreshGrid(){
    		DSRequest request = null;
    		if (paging!=null && paging.getOnePage()){
    			request = new DSRequest();
    			request.setStartRow(paging.getStartRow());
    			request.setEndRow(paging.getEndRow());
    			//request.setSortBy(dataGrid.getSort());  //TODO, there is a bug here, the request sortby is not set!
    			if (paging.getSortBy()!=null){
    				SortSpecifier sortSpecifier = null; 
    				if (paging.getSortorder().equals(Paging.ASCENDING)){
    					sortSpecifier = new SortSpecifier(paging.getSortBy(),SortDirection.ASCENDING);
    				}else{
    					sortSpecifier = new SortSpecifier(paging.getSortBy(),SortDirection.DESCENDING);
    				}
    				SortSpecifier[] array = new SortSpecifier[1];
    				array[0]=sortSpecifier;
    				request.setSortBy(array);
    			}
    			dataGrid.getDataSource().fetchData(dataGrid.getFilterEditorCriteria(), new DSCallback() {
    				public void execute(DSResponse response, Object rawData, DSRequest request) {
    					dataGrid.setData(response.getData());
    				}
    			},request);
    		}else{
    			dataGrid.invalidateCache();
    		}
    	}
    	
    	protected void saveForm() {
    		editForm.saveData(new DSCallback() {
       		 //Disable the primaryKeyField when the save is succesfull
    			public void execute(DSResponse response, Object rawData, DSRequest request) {
    				if (getPrimaryKeyFieldName()!=null){
                		 editForm.getField(getPrimaryKeyFieldName()).setDisabled(true);
                	 }
    				dirty=false;
    			}
    		});
    		
    	}  
    
    }
    9) The widget to edit/sort/filter the OEM table
    Code:
    /**
    Â** EditDistributorWidget.java [Apr 29, 2008]
    Â** 
    Â** Copyright (c) ExiNet, (Pty) Ltd. All Rights Reserved.
    Â**/
    package esos.client.widget.admin.oem;
    
    
    import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
    import esos.client.controller.ClientController;
    import esos.client.datasource.OemDS;
    import esos.shared.data.ibatisPOJO.Oem;
    import esos.shared.data.system.Language;
    import esos.client.widget.EditWidget;
    
    
    /**
     * This is the widget to add/edit and delete OEM (manufacturers). 
     * 
     * @author meindert
     */
    public class EditOemWidget extends EditWidget{ 
    	
    	protected final Language language = ClientController.getInstance().getLanguage();
    	
    	public EditOemWidget(String panelId) {
    		super(OemDS.getInstance(new Oem()),panelId);
    		initOemWidget();
    	}
    
    	private void initOemWidget(){
    		initWidget();
    	}
    	
    	@Override
    	public String getEntityName() {
    		return language.getOem();
    	}
    
    	@Override
    	public String getEntityNamePlural() {
    		return language.getOems();
    	}
    
    	@Override
    	public String getPrimaryKeyFieldName() {
    		return "oemCode";
    	}
    	
    	@Override
    	public void onRecordSelected(RecordClickEvent event) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	
    
    	
    }
    And last, here is the classpath;
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <classpath>
    	<classpathentry kind="src" path="src"/>
    	<classpathentry kind="src" output="test-classes" path="test"/>
    	<classpathentry kind="con" path="com.google.gwt.eclipse.core.GWT_CONTAINER"/>
    	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
    	<classpathentry kind="lib" path="war/WEB-INF/lib/log4j-1.2.14.jar"/>
    	<classpathentry kind="lib" path="C:/Development/Jar/smartgwt-2.1/smartgwt.jar"/>
    	<classpathentry kind="lib" path="war/WEB-INF/lib/ibatis-2.3.4.726.jar" sourcepath="C:/Development/ibatis/src/ibatis-src.zip"/>
    	<classpathentry kind="lib" path="war/WEB-INF/lib/spring.jar" sourcepath="C:/Development/spring-framework/src"/>
    	<classpathentry kind="lib" path="war/WEB-INF/lib/sqljdbc.jar"/>
    	<classpathentry kind="lib" path="war/WEB-INF/lib/aspectjweaver.jar"/>
    	<classpathentry kind="lib" path="war/WEB-INF/lib/commons-dbcp-1.2.2.jar"/>
    	<classpathentry kind="lib" path="war/WEB-INF/lib/commons-pool-1.4.jar"/>
    	<classpathentry kind="lib" path="war/WEB-INF/lib/gwt-servlet.jar"/>
    	<classpathentry kind="output" path="war/WEB-INF/classes"/>
    </classpath>
    Striped Eclipse project can be downloaded from www.hoving.co.za/Esos.zip
    Attached Files
    Last edited by meindert; 31 Mar 2010, 23:47.

    #2
    Thanks for sharing.

    Sanjiv

    Comment


      #3
      I used the same approach to remote paging,sorting and Filter.

      Paging and Sorting are working fine.

      I can not get the Filter Editor value, request.getCriteria() method gives null value for my property.

      request.getCriteria() .getAttribute ("name");

      Comment


        #4
        I have a lot of issues using the criteria. To work around it I use a filter object and populate this from the criteria.
        The filter is override by the criteria if the filter property is null, like this:
        if (to.getOemCode()==null)
        to.setOemCode(from.getAttributeAsString("oemCode"));


        in executeFetch:
        if (filter!=null) copyValues(request.getCriteria(),filter);

        Code:
        public static void copyValues(DataClass from, Brand to) {
          to.setBrandId(from.getAttributeAsString("brandId"));
          if (to.getOemCode()==null) 
            to.setOemCode(from.getAttributeAsString("oemCode"));
          to.setDescription(from.getAttributeAsString("description"));
          to.setDeleted(from.getAttributeAsBoolean("deleted"));
        }

        Comment


          #5
          Thanks for sharing.

          thank you very much.

          Comment

          Working...
          X