Project

General

Profile

Download (14.5 KB) Statistics
| Branch: | Tag: | Revision:
1
package eu.etaxonomy.cdm.vaadin.view.dbstatus;
2

    
3
import java.sql.SQLException;
4
import java.util.ArrayList;
5
import java.util.Arrays;
6
import java.util.HashMap;
7
import java.util.HashSet;
8
import java.util.List;
9
import java.util.Map;
10
import java.util.Set;
11

    
12
import com.vaadin.annotations.AutoGenerated;
13
import com.vaadin.data.Container;
14
import com.vaadin.data.Property;
15
import com.vaadin.data.Property.ValueChangeListener;
16
import com.vaadin.data.util.BeanItemContainer;
17
import com.vaadin.event.ShortcutAction.KeyCode;
18
import com.vaadin.event.ShortcutAction.ModifierKey;
19
import com.vaadin.navigator.View;
20
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
21
import com.vaadin.server.VaadinSession;
22
import com.vaadin.ui.AbsoluteLayout;
23
import com.vaadin.ui.Button;
24
import com.vaadin.ui.Button.ClickEvent;
25
import com.vaadin.ui.Button.ClickListener;
26
import com.vaadin.ui.ComboBox;
27
import com.vaadin.ui.CustomComponent;
28
import com.vaadin.ui.DefaultFieldFactory;
29
import com.vaadin.ui.Field;
30
import com.vaadin.ui.Label;
31
import com.vaadin.ui.Notification;
32
import com.vaadin.ui.Table;
33
import com.vaadin.ui.Table.ColumnGenerator;
34

    
35
import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
36
import eu.etaxonomy.cdm.model.common.CdmBase;
37
import eu.etaxonomy.cdm.model.common.DefinedTermBase;
38
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
39
import eu.etaxonomy.cdm.model.description.Distribution;
40
import eu.etaxonomy.cdm.model.description.Feature;
41
import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
42
import eu.etaxonomy.cdm.model.description.TaxonDescription;
43
import eu.etaxonomy.cdm.model.location.NamedArea;
44
import eu.etaxonomy.cdm.model.taxon.Taxon;
45
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
46
import eu.etaxonomy.cdm.vaadin.component.HorizontalToolbar;
47
import eu.etaxonomy.cdm.vaadin.container.CdmSQLContainer;
48

    
49
public class DistributionTableView extends CustomComponent implements IDistributionTableComponent, View{
50

    
51
	/*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
52

    
53
	/**
54
     *
55
     */
56
    private static final long serialVersionUID = 1L;
57
    @AutoGenerated
58
	private AbsoluteLayout mainLayout;
59
	@AutoGenerated
60
	private Table table_1;
61
	
62
	private Taxon currentTaxon;
63
	
64
	private DistributionTableComponentListener listener;
65
	
66
	ArrayList<String> columnList;
67
	ArrayList<String> headerList;
68
	private HorizontalToolbar toolbar;
69
	
70
	/**
71
	 * The constructor should first build the main layout, set the
72
	 * composition root and then do any custom initialization.
73
	 *
74
	 * The constructor will not be automatically regenerated by the
75
	 * visual editor.
76
	 */
77
	public DistributionTableView() {
78
		buildMainLayout();
79
		setCompositionRoot(mainLayout);
80
		createEditClickListener();
81
		
82
	}
83
	
84
	@Override
85
	public void addListener(DistributionTableComponentListener listener) {
86
	   this.listener = listener;
87
	}
88

    
89
	@AutoGenerated
90
	private AbsoluteLayout buildMainLayout() {
91
		// common part: create layout
92
		mainLayout = new AbsoluteLayout();
93
		mainLayout.setImmediate(false);
94
		mainLayout.setWidth("100%");
95
		mainLayout.setHeight("100%");
96

    
97
		// top-level component properties
98
		setWidth("100.0%");
99
		setHeight("100.0%");
100
		//Horizontal Toolbar
101
		toolbar = new HorizontalToolbar();
102
		mainLayout.addComponent(toolbar, "top:0.0px;right:0.0px;");
103
		
104
		// table_1
105
		table_1 = new Table();
106
		table_1.setImmediate(false);
107
		table_1.setWidth("100.0%");
108
		table_1.setHeight("100.0%");
109
		mainLayout.addComponent(table_1, "top:75px;right:0.0px;");
110

    
111
		return mainLayout;
112
	}
113

    
114
    /* (non-Javadoc)
115
     * @see com.vaadin.navigator.View#enter(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent)
116
     */
117
    @Override
118
    public void enter(ViewChangeEvent event) {
119
        // TODO Auto-generated method stub
120

    
121
    }
122

    
123

    
124
    
125
	public void dataBinding() throws SQLException{
126

    
127
//		container.addNestedContainerProperty("dDTO.status");
128
//		final LazyLoadedContainer container = listener.getLazyLoadedContainer();
129
//		Set<DefinedTermBase> chosenTerms = listener.getChosenTerms();
130
//		generateDsitributionColumn(chosenTerms);
131
		
132
		CdmSQLContainer container = listener.getSQLContainer();
133
		
134
		table_1.setContainerDataSource(container);
135
		table_1.setColumnReorderingAllowed(true);
136
		table_1.setSortEnabled(true);
137
//		setVisibleColumns(columns);
138
//		Object[] visibleColumns = columnList.toArray();
139
//		table_1.setVisibleColumns(visibleColumns);
140
//		table_1.setColumnHeaders(headerList.toArray(new String[headerList.size()]));//new String[]{"Taxon", "Rang"});// ,"Deutschland"
141
		
142
		table_1.setColumnCollapsingAllowed(true);
143
		table_1.setSelectable(true);
144
//		table_1.setSizeUndefined();
145
//		setSizeFull();
146
		table_1.setPageLength(20);
147
		table_1.setFooterVisible(true);
148
		table_1.setColumnFooter("Taxon", "Total amount of Taxa displayed: " + container.size());
149

    
150
		table_1.setCacheRate(10);
151
	}
152
    
153
    
154
    void generateDsitributionColumn(Set<DefinedTermBase> terms){
155
		columnList = new ArrayList<String>(Arrays.asList(new String[]{"fullTitleCache","rank"}));
156
		headerList = new ArrayList<String>(Arrays.asList(new String[]{"Taxon","Rang"}));
157
		for(final DefinedTermBase dt : terms){
158
			columnList.add(dt.getTitleCache());
159
			headerList.add(dt.getTitleCache());
160
//			container.addContainerProperty(dt.getTitleCache(), String.class, null);
161
			
162
			table_1.addContainerProperty(dt.getTitleCache(), String.class, null);
163
			try{
164
				table_1.addGeneratedColumn(dt.getTitleCache(), new ColumnGenerator() {
165
					public Object generateCell(Table source, Object itemId, Object columnId) {
166
						Label tf = new Label();
167
						ComboBox box = null;
168
						if(itemId instanceof TaxonNode){
169
							TaxonNode tn = CdmBase.deproxy((TaxonNode) itemId, TaxonNode.class);
170
							Taxon taxon = CdmBase.deproxy(tn.getTaxon(), Taxon.class);
171
							taxon = (Taxon) listener.getTaxonService().load(taxon.getUuid());
172
							HashMap<DescriptionElementBase, Distribution> map = getDistribution(taxon);
173
							
174
							List<PresenceAbsenceTerm> listTerm = listener.getPresenceAbsenceTerms();
175
							BeanItemContainer<PresenceAbsenceTerm> termContainer = new BeanItemContainer<PresenceAbsenceTerm>(PresenceAbsenceTerm.class);
176
							termContainer.addAll(listTerm);
177
							box = new ComboBox("Occurrence Status: ", termContainer);
178
							box.setImmediate(true);
179
							
180
							if(map != null){
181
								/** update field **/
182
								DescriptionElementBase deb = null; 
183
								Distribution db = null;
184
								for(Map.Entry<DescriptionElementBase, Distribution> entry : map.entrySet()){
185
									deb = entry.getKey();
186
									db = entry.getValue();
187
								}
188
								if(table_1.isEditable()){
189
									box = updateDistributionField(deb, db, termContainer, box, taxon);
190
								}else{
191
									if(db.getStatus() != null){
192
									tf.setValue(db.getStatus().toString());
193
									}else{
194
										//FIXME: case for delete?
195
										Notification.show("Possible Error for " +taxon.getTitleCache() + " for Distribution: " + db.getArea().getTitleCache(), Notification.Type.TRAY_NOTIFICATION);
196
										tf.setValue("-");
197
									}
198
								}
199
							}else{
200
								/** create distribution if it does not exist and set the status **/
201
								if(table_1.isEditable()){
202
									box = createDistributionField(taxon, termContainer, box);
203
								}else{
204
									tf.setValue("-");
205
								}
206
							}
207
							
208
						}
209
						
210
						if(table_1.isEditable()){
211
							return box;
212
						}else{
213
							return tf;
214
						}
215
					}
216

    
217
					private ComboBox createDistributionField(
218
							final Taxon taxon,
219
							BeanItemContainer<PresenceAbsenceTerm> termContainer,ComboBox box) {
220
						final ComboBox box2 = box;
221
						box.addValueChangeListener(new ValueChangeListener() {
222

    
223
							@Override
224
							public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
225
								NamedArea area = (NamedArea) dt;
226
								Distribution db = Distribution.NewInstance(area, (PresenceAbsenceTerm) box2.getValue());
227
					               Set<TaxonDescription> descriptions = taxon.getDescriptions();
228
				                    if (descriptions != null) {
229
				                        for (TaxonDescription desc : descriptions) {
230
				                            // add to first taxon description
231
				                            desc.addElement(db);
232
											listener.getDescriptionService().saveOrUpdate(desc);
233
				                            break;
234
				                        }
235
				                    } else {// there are no TaxonDescription yet.
236
				                        TaxonDescription td = TaxonDescription.NewInstance(taxon);
237
				                        td.addElement(db);
238
				                        taxon.addDescription(td);
239
				                        listener.getTaxonService().saveOrUpdate(taxon);
240
				                    }
241
							}
242
						
243
						});
244
						
245
						
246
						return box;
247
					}
248

    
249
					private HashMap<DescriptionElementBase, Distribution> getDistribution(Taxon taxon){
250
						Set<Feature> setFeature = new HashSet<Feature>(Arrays.asList(Feature.DISTRIBUTION()));
251
						List<DescriptionElementBase> listTaxonDescription = listener.listDescriptionElementsForTaxon(taxon, setFeature);
252
						for(DescriptionElementBase deb : listTaxonDescription){
253
							if(deb instanceof Distribution){
254
								Distribution db = (Distribution)deb;
255
								String titleCache = dt.getTitleCache();
256
								if(db.getArea().getTitleCache().equalsIgnoreCase(titleCache)){
257
									HashMap<DescriptionElementBase, Distribution> map = new HashMap<DescriptionElementBase, Distribution>();
258
									map.put(deb, db);
259
									return map;
260
								}
261
							}
262
						}
263
						return null;
264
					}
265
					
266
					private ComboBox updateDistributionField(DescriptionElementBase deb, Distribution db, BeanItemContainer<PresenceAbsenceTerm> termContainer, ComboBox box, Taxon taxon) {
267
						final Distribution db2 = db;
268
						final DescriptionElementBase deb2 = deb;
269
						box.setValue(db.getStatus());
270
						final ComboBox box2 = box;
271
						final Taxon taxon2 = taxon;
272
						box.addValueChangeListener(new ValueChangeListener() {
273
							
274
							private static final long serialVersionUID = 1L;
275

    
276
							@Override
277
							public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
278
								if(box2.getValue() == null){//delete descriptionElementBase
279
									listener.getDescriptionService().deleteDescriptionElement(deb2);
280
									listener.getTaxonService().saveOrUpdate(taxon2);
281
									Notification.show("Delete Status", Notification.Type.TRAY_NOTIFICATION);
282
								}else{
283
									db2.setStatus((PresenceAbsenceTerm)box2.getValue());
284
									listener.getDescriptionService().saveDescriptionElement(deb2);
285
									Notification.show("DescriptionService wrote", Notification.Type.TRAY_NOTIFICATION);
286
								}
287
							}
288
						});
289
						return box;
290
					}
291
				});
292
			}catch(IllegalArgumentException e){
293
				e.printStackTrace();
294
			}
295
		}	
296
    }
297
    
298
    private DefaultFieldFactory createDefaulfielFactory() {
299
		DefaultFieldFactory fieldFactory = new DefaultFieldFactory() {
300
			private static final long serialVersionUID = 1L;
301
			@Override
302
			public Field createField(Container container, Object itemId,
303
					Object propertyId, com.vaadin.ui.Component uiContext) {
304
				Property containerProperty = container.getContainerProperty(itemId, propertyId);
305
				if("fullTitleCache".equals(propertyId)){
306
					return null;
307
				}
308
				if("rank".equals(propertyId)){
309
					return null;
310
				}
311
//				if("Berlin".equals(propertyId)){
312
//						List<PresenceAbsenceTermBase> listTerm = termService.list(PresenceAbsenceTermBase.class, null, null, null, DESCRIPTION_INIT_STRATEGY);
313
//						BeanItemContainer<PresenceAbsenceTermBase> termContainer = new BeanItemContainer<PresenceAbsenceTermBase>(PresenceAbsenceTermBase.class);
314
//						termContainer.addAll(listTerm);
315
//						final ComboBox box = new ComboBox("Occurrence Status: ", termContainer);
316
//						Item item = container.getItem(itemId);
317
//						box.setValue(item);
318
//						toolbar.getSaveButton().setCaption("Save Data *");
319
//						return box;
320
//					}
321
				return super.createField(container, itemId, propertyId, uiContext);
322
			}
323
		};
324
		return fieldFactory;
325
	}
326

    
327

    
328
	private void createEditClickListener(){
329
//		Button detailButton = toolbar.getDetailButton();
330
//		detailButton.setCaption("Detail View");
331
//		detailButton.addClickListener(new ClickListener() {
332
//
333
//			@Override
334
//			public void buttonClick(ClickEvent event) {
335
//				try{
336
//				if(currentTaxon != null){
337
//					List<DescriptionElementBase> listDescriptions = descriptionService.listDescriptionElementsForTaxon(currentTaxon, null, null, null, null, DESCRIPTION_INIT_STRATEGY);
338
//					DetailWindow dw = new DetailWindow(currentTaxon, listDescriptions);
339
//					Window window = dw.createWindow();
340
//					getUI().addWindow(window);
341
//				}else{
342
//					Notification.show("Please select a Taxon.", Notification.Type.HUMANIZED_MESSAGE);
343
//				}
344
//				}catch(Exception e){
345
//					Notification.show("Unexpected Error, \n\n Please log in again!", Notification.Type.WARNING_MESSAGE);
346
//					logger.info(e);
347
//					authenticationController.logout();
348
//				}
349
//			}
350
//		});
351

    
352

    
353
		Button saveButton = toolbar.getSaveButton();
354
		saveButton.setClickShortcut(KeyCode.S, ModifierKey.CTRL);
355
		saveButton.setDescription("Shortcut: CTRL+S");
356
		saveButton.setCaption("Save Data");
357
		saveButton.addClickListener(new ClickListener() {
358
			private static final long serialVersionUID = 1L;
359
			@Override
360
			public void buttonClick(ClickEvent event) {
361
				ConversationHolder conversationHolder = (ConversationHolder) VaadinSession.getCurrent().getAttribute("conversation");
362
				try{
363
					conversationHolder.commit();
364
				}catch(Exception stateException){
365
					//TODO create Table without DTO
366
				}
367
				Notification.show("Data saved", Notification.Type.HUMANIZED_MESSAGE);
368
				table_1.setEditable(false);
369
				toolbar.getSaveButton().setCaption("Save Data");
370
			}
371
		});
372

    
373
		Button editButton = toolbar.getEditButton();
374
		editButton.setClickShortcut(KeyCode.E, ModifierKey.CTRL);
375
		editButton.setDescription("Shortcut: CTRL+e");
376
		editButton.addClickListener(new ClickListener() {
377
			private static final long serialVersionUID = 1L;
378

    
379
			@Override
380
			public void buttonClick(ClickEvent event) {
381
				if(table_1.isEditable() == false){
382
					table_1.setEditable(true);
383
//					taxonTable.removeGeneratedColumn("Berlin");
384
//					taxonTable.refreshRowCache();
385
				}else{
386
					table_1.setEditable(false);
387
					table_1.refreshRowCache();
388
				}
389
			}
390
		});
391

    
392
		//FIXME with new SQL CONTAINER
393
//		table_1.addItemClickListener(new ItemClickListener() {
394
//
395
//			@Override
396
//			public void itemClick(ItemClickEvent event) {
397
//				Object taxonbean = ((BeanItem<?>)event.getItem()).getBean();
398
//				if(taxonbean instanceof CdmTaxonTableCollection){
399
//					CdmTaxonTableCollection red = (CdmTaxonTableCollection) taxonbean;
400
//					currentTaxon = red.getTaxon();
401
//				}
402
//			}
403
//		});
404
	}
405

    
406
}
(2-2/4)