Announcement

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

    Originally posted by mnenchev
    I do not have deployable sample at the moment but here is the code connected with the problem:
    I have asset:newsDays one to many relationship
    Code:
    //view
    	
    		final DynamicForm newsDayForm = new DynamicForm();
    		newsDayForm.setDataSource(NewsDaysDataSource.getInstance());
    
    // newsDaysDS
    	public NewsDaysDataSource() {
    		setClientOnly(true);
    
    		pk = new DataSourceIntegerField("id", "News Day Id");
    		pk.setPrimaryKey(true);
    		pk.setHidden(true);
    		addField(pk);
    
    		assetField = new DataSourceIntegerField("assetId");
    		assetField.setCanEdit(true);
    		assetField.setEditorType(new WebSelectItem(AssetJsonDataSource.getInstance()));
    		assetField.setForeignKey("assetsDS.key");
    		assetField.setRequired(true);
    		addField(assetField);
    		dateField = new DataSourceDateField("date", "Date");
    		final DateRangeValidator validator = new DateRangeValidator();
    		validator.setMin(new Date());
    		dateField.setRequired(true);
    		dateField.setValidators(validator);
    		addField(dateField);
    		intervalField = new DataSourceIntegerField("interval", "Interval");
    		final IntegerRangeValidator integerValidator = new IntegerRangeValidator();
    		integerValidator.setMin(0);
    		intervalField.setValidators(integerValidator);
    		intervalField.setRequired(true);
    		addField(intervalField);
    	}
    
    // AssetDS
    protected DataSourceIntegerField key;
    	protected DataSourceField value;
    	
    	public AssetJsonDataSource() {
    		key = new DataSourceIntegerField("key");
    		key.setHidden(true);
    		key.setPrimaryKey(true);
    		addField(key);
    		value = new DataSourceTextField("value");
    		addField(value);
    		setClientOnly(true);
    		this.setID("assetsDS");
    	}
    	
    	@Override
    	protected void executeAdd(String requestId, DSRequest request, DSResponse response) {
    		
    	}
    
    	@Override
    	protected void executeFetch(final String requestId, DSRequest request, final DSResponse response) {
    		final AssetServiceAsync service = ServiceUtils.getAssetServiceAsync();
    		service.getAssetsMap(new KeyValueJsonAsyncCallback() {
    			@Override
    			public void responseFailure(Throwable e) {
    				SC.warn("ERROR : " + e.getMessage(), null);
    				response.setStatus(RPCResponse.STATUS_FAILURE);
    				processResponse(requestId, response);
    			}
    			@Override
    			public void responseSuccess(Record[] records) {
    				response.setData(records);
    				processResponse(requestId, response);				
    			}
    
    		});
    	}
    
    	@Override
    	protected void executeRemove(String requestId, DSRequest request, DSResponse response) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	protected void executeUpdate(String requestId, DSRequest request, DSResponse response) {
    		// TODO Auto-generated method stub
    		
    	}
    	
    	@Override
    	protected Object getValueOf(String from, String fieldName) {
    		return null;
    	}
    KeyValueJsonAsyncCallback just transforms json key:value to Record
    My AssetJsonDataSource is tested and working with SelectItems.

    I would need to see all your code to understand what you're doing...

    It looks like you're using JSON and client side only I'm using RPC and Objects (server side only).

    Your declarations are a lot different from what I have so I would have to see it all.

    Comment


      Code:
      // view code: one SelectItems filled with assets and one grid, that shows all // news days for the selected asset
      
      public class NewsDayPanel extends VLayout {
      	private static final String DESCRIPTION = "News Days";
      
      	public static class Factory implements PanelFactory {
      
      		private String id;
      
      		public Canvas create() {
      			final NewsDayPanel panel = new NewsDayPanel();
      			id = panel.getID();
      			return panel;
      		}
      
      		public String getID() {
      			return id;
      		}
      
      		public String getDescription() {
      			return DESCRIPTION;
      		}
      	}
      
      	private ListGrid grid;
      	private SelectItem assets;
      	private AddEditDialog addEditDialog;
      
      	public NewsDayPanel() {
      		this.setWidth100();
      		this.setHeight100();
      		this.setMembersMargin(10);
      
      		// init grid
      		grid = new ListGrid();
      		grid.setAlternateRecordStyles(true);
      		grid.setWidth(600);
      		grid.setHeight(400);
      		grid.setAutoFitData(Autofit.VERTICAL);
      		grid.setAutoFitMaxRecords(15);
      		grid.setShowAllRecords(true);
      		grid.setEditEvent(ListGridEditEvent.CLICK);
      		grid.setDataSource(NewsDaysDataSource.getInstance());
      		grid.setAlign(Alignment.CENTER);
      		grid.setSelectionType(SelectionStyle.SINGLE);
      		final ListGridField id = new ListGridField("id", "NewsDay Id");
      		final ListGridField date = new ListGridField("date", "Date");
      		grid.setDateFormatter(DateDisplayFormat.TOEUROPEANSHORTDATE);
      		final ListGridField interlval = new ListGridField("interval", "Interval");
      		final DynamicForm form = new DynamicForm();
      		grid.setFields(id, date, interlval);
      		form.setWidth(500);
      		form.setNumCols(2);
      
      		// init assets
      		assets = new SelectItem("Assets");
      		assets.setDefaultToFirstOption(false);
      		assets.setDisplayField("value");
      		assets.setValueField("key");
      		assets.setOptionDataSource(AssetJsonDataSource.getInstance());
      		assets.addChangedHandler(new ChangedHandler() {
      			@Override
      			public void onChanged(ChangedEvent event) {
      				loadUserData();
      
      			}
      		});
      
      		form.setFields(assets);
      		this.addMember(form);
      		this.addMember(grid);
      
      		// add edit form
      		final DynamicForm newsDayForm = new DynamicForm();
      		newsDayForm.setDataSource(NewsDaysDataSource.getInstance());
      		// init buttons
      		final IButton newButton = new IButton("New");
      		newButton.addClickHandler(new ClickHandler() {
      			@Override
      			public void onClick(ClickEvent event) {
      				if (addEditDialog == null) {
      					addEditDialog = new AddEditDialog(newsDayForm, new BooleanCallback() {
      						@Override
      						public void execute(Boolean value) {
      							if (value) {
      								if (newsDayForm.validate()) {
      									newsDayForm.saveData(new DSCallback() {
      									
      										@Override
      										public void execute(DSResponse response, Object rawData, DSRequest request) {
      											final Record rec = new Record(request.getData());
      												if (rec.getAttributeAsInt("assetId") != (Integer) assets.getValue()) {
      													loadUserData();
      												}
      										}
      									});
      									addEditDialog.hide();
      								}
      							} else {
      								addEditDialog.hide();
      							}
      						}
      					});
      					addEditDialog.setHeight(150);
      					addEditDialog.setWidth(500);
      				}
      				addEditDialog.showForAdd();
      			}
      		});
      
      		final IButton deleteButton = new IButton("Delete");
      		deleteButton.setLeft(110);
      		deleteButton.addClickHandler(new ClickHandler() {
      			@Override
      			public void onClick(ClickEvent event) {
      				final ListGridRecord selectedRecord = grid.getSelectedRecord();
      				if (selectedRecord != null) {
      					grid.removeData(selectedRecord);
      				} else {
      					SC.warn("Select a News Day first!", null);
      				}
      			}
      		});
      
      		// final IButton cancelButton = new IButton("Cancel");
      		// cancelButton.setLeft(220);
      		// cancelButton.addClickHandler(new ClickHandler() {
      		// @Override
      		// public void onClick(ClickEvent event) {
      		// grid.discardAllEdits();
      		// }
      		// });
      
      		final HLayout buttons = new HLayout();
      		buttons.setMembersMargin(210);
      		buttons.addChild(newButton);
      		buttons.addChild(deleteButton);
      
      		this.addMember(buttons);
      	}
      
      	private void loadUserData() {
      		grid.invalidateCache();
      		final Integer assetId = (Integer) assets.getValue();
      		if (assetId == null) {
      			return;
      		}
      
      		final DSRequest request = new DSRequest();
      		request.setAttribute("assetId", assetId);
      		grid.fetchData(null, null, request);
      	}
      }
      
      // assets data source
      
      public class AssetJsonDataSource extends BaseKeyValueDataSource {
      
      
      	private static AssetJsonDataSource instance = null;
      	private static Object sync = new Object();
      	
      	public static AssetJsonDataSource getInstance() {
      		if (instance == null) {
      			synchronized (sync) {
      				if (instance == null) {
      					instance = new AssetJsonDataSource();
      				}
      			}
      		}
      		return instance;
      	}
      	
      	public AssetJsonDataSource() {
      		super();
      		this.setID("assetsDS");
      	}
      	
      	@Override
      	protected void executeAdd(String requestId, DSRequest request, DSResponse response) {
      		
      	}
      
      	@Override
      	protected void executeFetch(final String requestId, DSRequest request, final DSResponse response) {
      		final AssetServiceAsync service = ServiceUtils.getAssetServiceAsync();
      		service.getAssetsMap(new KeyValueJsonAsyncCallback() {
      			@Override
      			public void responseFailure(Throwable e) {
      				SC.warn("ERROR : " + e.getMessage(), null);
      				response.setStatus(RPCResponse.STATUS_FAILURE);
      				processResponse(requestId, response);
      			}
      			@Override
      			public void responseSuccess(Record[] records) {
      				response.setData(records);
      				processResponse(requestId, response);				
      			}
      
      		});
      	}
      
      	@Override
      	protected void executeRemove(String requestId, DSRequest request, DSResponse response) {
      		// TODO Auto-generated method stub
      		
      	}
      
      	@Override
      	protected void executeUpdate(String requestId, DSRequest request, DSResponse response) {
      		// TODO Auto-generated method stub
      		
      	}
      	
      	@Override
      	protected Object getValueOf(String from, String fieldName) {
      		return null;
      	}
      
      
      }
      
      // key-value data source
      public abstract class BaseKeyValueDataSource  extends GenericGwtRpcDataSource<String> {
      
      	protected DataSourceIntegerField key;
      	protected DataSourceField value;
      	
      	public BaseKeyValueDataSource() {
      		key = new DataSourceIntegerField("key");
      		key.setHidden(true);
      		key.setPrimaryKey(true);
      		addField(key);
      		value = new DataSourceTextField("value");
      		addField(value);
      		setClientOnly(true);
      	}
      }
      
      // key - value callback
      public abstract class KeyValueJsonAsyncCallback implements AsyncCallback<List<String>> {
      
      		@Override
      		public void onSuccess(List<String> data) {
      			final Record[] records = new Record[data.size()];
      			int i = 0;
      			for(final String json : data) {
      				final JSONObject obj = (JSONObject) JSONParser.parse(json);
      				final Record r = new Record(obj.getJavaScriptObject());
      				records[i++] = r;
      			}
      			responseSuccess(records);
      		}
      		
      		@Override
      		public void onFailure(Throwable e) {
      			responseFailure(e);
      		}
      
      		public abstract void responseSuccess(Record[] records);
      		public abstract void responseFailure(Throwable e);
      }

      Comment


        Code:
        // news days data source
        
        
        public class NewsDaysDataSource extends GenericGwtRpcDataSource<NewsDayDTO> {
        
        	private static NewsDaysDataSource instance = null;
        	private static Object sync = new Object();
        
        	public static NewsDaysDataSource getInstance() {
        		if (instance == null) {
        			synchronized (sync) {
        				if (instance == null) {
        					instance = new NewsDaysDataSource();
        				}
        			}
        		}
        		return instance;
        	}
        
        	private DataSourceIntegerField pk;
        	private DataSourceField assetField;
        	private DataSourceDateField dateField;
        	private DataSourceField intervalField;
        
        	public NewsDaysDataSource() {
        		setClientOnly(true);
        
        		pk = new DataSourceIntegerField("id", "News Day Id");
        		pk.setPrimaryKey(true);
        		pk.setHidden(true);
        		addField(pk);
        
        		assetField = new DataSourceIntegerField("assetId");
        		assetField.setCanEdit(true);
        		assetField.setEditorType(new WebSelectItem(AssetJsonDataSource.getInstance()));
        		assetField.setForeignKey("assetsDS.key");
        		assetField.setRequired(true);
        		addField(assetField);
        		dateField = new DataSourceDateField("date", "Date");
        		final DateRangeValidator validator = new DateRangeValidator();
        		validator.setMin(new Date());
        		dateField.setRequired(true);
        		dateField.setValidators(validator);
        		addField(dateField);
        		intervalField = new DataSourceIntegerField("interval", "Interval");
        		final IntegerRangeValidator integerValidator = new IntegerRangeValidator();
        		integerValidator.setMin(0);
        		intervalField.setValidators(integerValidator);
        		intervalField.setRequired(true);
        		addField(intervalField);
        	}
        
        	@Override
        	protected void executeAdd(final String requestId, final DSRequest request, final DSResponse response) {
        		final JavaScriptObject data = request.getData();
        		final ListGridRecord rec = new ListGridRecord(data);
        		final NewsDayDTO dto = new NewsDayDTO();
        		dto.setDate(rec.getAttributeAsDate("date"));
        		dto.setAssetId(rec.getAttributeAsInt("assetId"));
        		dto.setInterval(rec.getAttributeAsInt("interval"));
        		final NewsDayServiceAsync service = ServiceUtils.getNewsDayServiceAsync();
        		service.addNewsDay(dto, new AsyncCallback<Integer>() {
        			@Override
        			public void onSuccess(Integer id) {
        				rec.setAttribute("id",id);
        				request.setData(rec.getJsObj());
        				processResponse(requestId, response);
        			}
        
        			@Override
        			public void onFailure(Throwable e) {
        				response.setStatus(RPCResponse.STATUS_FAILURE);
        				processResponse(requestId, response);
        				SC.warn("Error adding News Day : " + e.getMessage(), null);
        			}
        		});
        
        	}
        @Override
        	protected void executeFetch(final String requestId, DSRequest request, final DSResponse response) {
        		final Integer assetId = request.getAttributeAsInt("assetId");
        		if (assetId == null) {
        			return;
        		}
        		final NewsDayServiceAsync service = ServiceUtils.getNewsDayServiceAsync();
        		service.getNewsDaysByAssetId(assetId, new AsyncCallback<List<NewsDayDTO>>() {
        			@Override
        			public void onSuccess(List<NewsDayDTO> data) {
        				final ListGridRecord[] records = new ListGridRecord[data.size()];
        				for (int i = 0; i < data.size(); i++) {
        					final ListGridRecord r = new ListGridRecord();
        					copyValues(data.get(i), r);
        					records[i] = r;
        				}
        				response.setData(records);
        				processResponse(requestId, response);
        			}
        
        			@Override
        			public void onFailure(Throwable e) {
        				response.setStatus(RPCResponse.STATUS_FAILURE);
        				processResponse(requestId, response);
        			}
        		});
        	}
        
        	@Override
        	protected void executeRemove(final String requestId, DSRequest request, final DSResponse response) {
        		final JavaScriptObject data = request.getData();
        		final ListGridRecord rec = new ListGridRecord(data);
        		final int id = rec.getAttributeAsInt("id");
        		final NewsDayServiceAsync service = ServiceUtils.getNewsDayServiceAsync();
        		service.deleteNewsDay(id, new AsyncCallback<Void>() {
        			@Override
        			public void onSuccess(Void data) {
        				final ListGridRecord[] list = new ListGridRecord[1];
        				list[0] = rec;
        				response.setData(list);
        				processResponse(requestId, response);
        			}
        
        			@Override
        			public void onFailure(Throwable e) {
        				response.setStatus(RPCResponse.STATUS_FAILURE);
        				processResponse(requestId, response);
        				SC.warn("Error deleting News Day: " + e.getMessage(), null);
        			}
        		});
        	}
        
        	@Override
        	protected void executeUpdate(String requestId, DSRequest request, DSResponse response) {
        
        	}
        
        	@Override
        	protected Object getValueOf(NewsDayDTO from, String fieldName) {
        		if (pk.getName().equals(fieldName)) {
        			return from.getId();
        		} else if (dateField.getName().equals(fieldName)) {
        			return from.getDate();
        		} else if (intervalField.getName().equals(fieldName)) {
        			return from.getInterval();
        		} else if (assetField.getName().equals(fieldName)) {
        			return from.getAssetId();
        		}
        		return null;
        	}
        }
        This I do receive data from RPC service, but i have callback that says how to transform the data coming from the rpc in json. I the assets select item that is not part from the dynamic form, but serves as a filter for the grid everything works, the assets are loaded as key/value. May be the problem is in the data presentation( json?)
        The addeditDialog is just a window that displays the form.
        Do you need the RPC implementations?
        Regards.

        Comment


          Originally posted by mnenchev
          Well, you are right for the 2). But i want to keep in the list grid only records that pass where clause for example booleanFoo = true (in the database). And if the user uncheck booleanFoo for 3 records and pres update their booleanFoo is updated in the database and they are removed from the list grid why should i force new fetch if i know what i updated and what i should remove from the listgrid. The application is admin iterface that will not be used from 2 or more user simultaneously, so making new fetch is unneeded.
          Any response on this one?

          Comment


            Originally posted by chetan.phanse
            Any response on this one?
            What do you mean? On update you do not need to fetch the data again just update the edited row. But if you execute insert operation you do need to return the primary key(the id) of the grid record and then insert the new ListGridRecord with initialized id. That is in case you know that only one user can view/modify the screen at a time.

            Comment


              Possible pitfalls

              I just wanted to post those in case anyone would make some of the (quite long row of) mistakes I did.
              Hopefully it saves some time to someone...

              When implementing FETCH in your DataSource you better avoid trying to generalize it to Collection<T>. Compiler won't complain but you are asking for HTTP 500. (I guess it has something to do with how is Collection type treated during the process of serialization.) List<T> works just fine.

              When implementing REMOVE (or any non read-only operation) do not forget to mark exactly one of your DataSourceFields as primaryKey.
              Without that your DSResponse.getData() will return empty array.
              Last edited by jzaruba; 19 Sep 2009, 14:41.

              Comment


                fetchData() working, fetchData(Criteria) does not

                Hi All


                I'm using one of the older generalized<T> versions of GWT-RPC datasource.

                Everything seems to work fine as long as i stick to fetchData().
                I can retrieve records, add records, edit them and the results are indeed updated in the database. Sofar so good.

                However, when i use fetchData(criteria), I either get all records or no records.
                I toyed with setFetchMode(), setUseClientFiltering, etc but to no avail, i either get everything or i get nothing.

                My criteria is as basic as it gets:
                Code:
                     		Criteria criteria=new Criteria();
                       		criteria.addCriteria("Name","test");  
                                projectList.fetchData(criteria);
                My database is very small, only 20 record or so.

                It is very well possible that i misunderstood some of the basics of either gwt-rpc or smartGWT, i'm not that experienced with either.

                So, what am i missing here? Can somebody please point me in the right direction?

                Comment


                  Set custom object to Criteria

                  Hi, All.

                  How can i set custom object to Criteria?

                  For example:
                  Code:
                   
                         		Criteria criteria=new Criteria();
                         		criteria.addCriteria("customObject", new CustomObject());  
                                  listGrid.fetchData(criteria);    
                  
                  public void executeFetch(final String requestId, final DSRequest request, final DSResponse response) {
                  Object object = request.getCriteria().getAttributeAsObject("customObject"));
                  }
                  In execute fetch i get JavaScriptObject and not convert to my CustomObject. May be exists another methods of getting my ccriteria?

                  Comment


                    Alius: Updated Code

                    Alius: Is there any new sample code for TestAdvDataSource.
                    I downloaded this zip file, and it seems to work great, but I have a couple of issues. So, I was looking for updated source code.

                    There was the SmartGWT-Extensions at Google as created by Nicholas.Lotz, but there seems to be a bug in it.

                    Any help would be much appreciated. I'm on a tight deadline now, and my last 4 messages here got no replies from anyone.

                    Thanks for any help!
                    Tom

                    Comment


                      Originally posted by BeezeR
                      Hi, All.

                      How can i set custom object to Criteria?

                      For example:
                      Code:
                       
                             		Criteria criteria=new Criteria();
                             		criteria.addCriteria("customObject", new CustomObject());  
                                      listGrid.fetchData(criteria);    
                      
                      public void executeFetch(final String requestId, final DSRequest request, final DSResponse response) {
                      Object object = request.getCriteria().getAttributeAsObject("customObject"));
                      }
                      In execute fetch i get JavaScriptObject and not convert to my CustomObject. May be exists another methods of getting my ccriteria?

                      I had the same problem. I found that it works by calling fetchData() directly on the datasource instead of on the listGrid. Also, it's only a problem in hosted mode.

                      Comment


                        Could someone PLZ post an example of using DynamicForm together with GWTRPCDataSource?

                        I'm very green on this, so I am only guessing I should be able to tell somehow the form to load a record/object from provided (GWTRPC)DataSource and populate (maybe not necessarilly create) its fields with the properties.

                        This is the closest answer I've been able to find in the SmartGWT ShowCase, but this example does not use 'real' DataSource.

                        Comment


                          Can you please upload DTObjectModel class?

                          Originally posted by mnenchev
                          Hi, could you give us, more detailed example? What is this DTObjectModel. Pleas provide some simple usage :).

                          Can you please upload DTObjectModel class?

                          Comment


                            Originally posted by ynaik
                            Can you please upload DTObjectModel class?
                            Hi, as you can see i was asking the same question as you did, but no one answered. I used the sample snippet to implement this generic functionality. I think that DTObject model is just base class for all your dtos.

                            public class DTObjectModel implements Serializable {

                            }
                            :-D

                            If you want i may upload detailed code that uses the lanceweber's sample, but i did not test it.
                            Last edited by mnenchev; 29 Sep 2009, 00:53.

                            Comment


                              Originally posted by mnenchev
                              Hi, as you can see i was asking the same question as you did, but no one answered. I used the sample snippet to implement this generic functionality. I think that DTObject model is just base class for all your dtos.

                              public class DTObjectModel implements Serializable {

                              }
                              :-D

                              If you want i may upload detailed code that uses the lanceweber's sample, but i did not test it.
                              Thank you very much your prompt reply, I will really appreciate if you can upload your detailed generic functionality code.

                              I will wait for your response.

                              Comment


                                Originally posted by ynaik
                                Thank you very much your prompt reply, I will really appreciate if you can upload your detailed generic functionality code.

                                I will wait for your response.
                                Hi, ynaik. I attached you sample code (just .java files). Home it helps you. I didn't tested, but it should work. If you find any bugs, or errors let me know. Only executeAdd method is implemented, but the others are in the same manner. If you improve the code paste it here :).
                                Download from here : http://rapidshare.com/files/28695615...ample.zip.html

                                All you have to do is to implement SmartGWTDataConvertor for each dto you want to use and create ds for it like this:
                                Code:
                                final SmartGWTDataSource<TestDTO, SmartGWTDataConverter<TestDTO>, DataServiceAsync<TestDTO>> ds = 
                                			new SmartGWTDataSource<TestDTO, SmartGWTDataConverter<TestDTO>, DataServiceAsync<TestDTO>>(new TestDataConverter(), ServiceUtils.getTestServiceAsync(), RecordType.GRID);
                                Last edited by mnenchev; 30 Sep 2009, 07:38.

                                Comment

                                Working...
                                X