Project

General

Profile

Download (17 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2017 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.vaadin.view.distributionStatus;
10

    
11
import java.sql.SQLException;
12
import java.util.ArrayList;
13
import java.util.Arrays;
14
import java.util.Collection;
15
import java.util.List;
16
import java.util.UUID;
17

    
18
import org.springframework.beans.factory.annotation.Autowired;
19
import org.springframework.orm.hibernate5.HibernateSystemException;
20
import org.springframework.security.core.GrantedAuthority;
21
import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer;
22

    
23
import com.vaadin.data.Item;
24
import com.vaadin.data.Property;
25
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
26
import com.vaadin.spring.annotation.SpringView;
27
import com.vaadin.spring.annotation.ViewScope;
28
import com.vaadin.ui.AbsoluteLayout;
29
import com.vaadin.ui.Button;
30
import com.vaadin.ui.Grid;
31
import com.vaadin.ui.Grid.FooterRow;
32
import com.vaadin.ui.ListSelect;
33
import com.vaadin.ui.Notification;
34
import com.vaadin.ui.Notification.Type;
35
import com.vaadin.ui.Table;
36
import com.vaadin.ui.UI;
37
import com.vaadin.ui.VerticalLayout;
38
import com.vaadin.ui.Window;
39

    
40
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
41
import eu.etaxonomy.cdm.i18n.Messages;
42
import eu.etaxonomy.cdm.model.common.CdmBase;
43
import eu.etaxonomy.cdm.model.common.Language;
44
import eu.etaxonomy.cdm.model.common.Representation;
45
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
46
import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
47
import eu.etaxonomy.cdm.model.taxon.Taxon;
48
import eu.etaxonomy.cdm.vaadin.component.DetailWindow;
49
import eu.etaxonomy.cdm.vaadin.component.DistributionToolbar;
50
import eu.etaxonomy.cdm.vaadin.container.CdmSQLContainer;
51
import eu.etaxonomy.cdm.vaadin.event.error.DelegatingErrorHandler;
52
import eu.etaxonomy.cdm.vaadin.event.error.HibernateSystemErrorHandler;
53
import eu.etaxonomy.cdm.vaadin.security.AccessRestrictedView;
54
import eu.etaxonomy.cdm.vaadin.util.CdmQueryFactory;
55
import eu.etaxonomy.cdm.vaadin.util.CdmSpringContextHelper;
56
import eu.etaxonomy.cdm.vaadin.util.DistributionEditorUtil;
57
import eu.etaxonomy.cdm.vaadin.view.AbstractPageView;
58

    
59
/**
60
 * @author freimeier
61
 * @since 18.10.2017
62
 *
63
 */
64
@ViewScope
65
@SpringView(name=DistributionTableViewBean.NAME)
66
public class DistributionTableViewBean
67
            extends AbstractPageView<DistributionTablePresenter>
68
            implements IDistributionTableView, AccessRestrictedView {
69

    
70
	private static final long serialVersionUID = 1L;
71
    public static final String NAME = "distGrid"; //$NON-NLS-1$
72

    
73
    @Autowired
74
    private DistributionToolbar toolbar;
75

    
76
	private Table table;
77
	private Grid grid;
78
	private FooterRow footerRow;
79

    
80
    private CdmSQLContainer container;
81
    private LazyQueryContainer gridcontainer;
82
	private AreaAndTaxonSettingsConfigWindow areaAndTaxonConfigWindow;;
83
	private DistributionStatusSettingsConfigWindow distributionStatusConfigWindow;
84

    
85
	public DistributionTableViewBean() {
86
		super();
87
	}
88

    
89
	private AbsoluteLayout initLayout() {
90
		AbsoluteLayout mainLayout = new AbsoluteLayout();
91
		mainLayout.setImmediate(false);
92
		mainLayout.setWidth("100%"); //$NON-NLS-1$
93
		mainLayout.setHeight("100%"); //$NON-NLS-1$
94

    
95
		setWidth("100.0%"); //$NON-NLS-1$
96
		setHeight("100.0%"); //$NON-NLS-1$
97

    
98
		//Horizontal Toolbar
99
		mainLayout.addComponent(toolbar, "top:0.0px;right:0.0px;"); //$NON-NLS-1$
100

    
101
		// table + formatting
102
		table = new Table(){
103
			private static final long serialVersionUID = -5148756917468804385L;
104

    
105
			@Override
106
			protected String formatPropertyValue(Object rowId, Object colId, Property<?> property) {
107
				String formattedValue = null;
108
				PresenceAbsenceTerm presenceAbsenceTerm = null;
109
				Object value = property.getValue();
110
				if(value instanceof String){
111
//					presenceAbsenceTerm = TermCacher.getInstance().getPresenceAbsenceTerm((String) value);
112
                    try {
113
                        presenceAbsenceTerm = (PresenceAbsenceTerm)CdmSpringContextHelper.getTermService().load(UUID.fromString((String)value));
114
                    }catch(IllegalArgumentException|ClassCastException e) {
115
                        // Not a PresenceAbsenceTerm Column
116
                    }
117
				}
118
				if(presenceAbsenceTerm != null){
119
					Representation representation = presenceAbsenceTerm.getRepresentation(Language.DEFAULT());
120
					if(representation!=null){
121
						if(DistributionEditorUtil.isAbbreviatedLabels()){
122
							formattedValue = representation.getAbbreviatedLabel();
123
						}
124
						else{
125
							formattedValue = representation.getLabel();
126
						}
127
					}
128
					if(formattedValue==null){
129
						formattedValue = presenceAbsenceTerm.getTitleCache();
130
					}
131
					return formattedValue;
132
				}
133
				return super.formatPropertyValue(rowId, colId, property);
134
			}
135
		};
136
		table.setImmediate(false);
137
		table.setWidth("100.0%");
138
		table.setHeight("100.0%");
139

    
140
        table.setColumnReorderingAllowed(true);
141
        table.setSortEnabled(false);
142

    
143
        table.setColumnCollapsingAllowed(true);
144
        table.setSelectable(true);
145
        table.setPageLength(20);
146
        table.setFooterVisible(true);
147
        table.setCacheRate(20);
148

    
149
		table.addItemClickListener(event -> {
150
            if(!(event.getPropertyId().toString().equalsIgnoreCase(CdmQueryFactory.TAXON_COLUMN))
151
            		&& !(event.getPropertyId().toString().equalsIgnoreCase(CdmQueryFactory.RANK_COLUMN))
152
            		// TODO: HACK FOR RL 2017, REMOVE AS SOON AS POSSIBLE
153
            		&& !(event.getPropertyId().toString().equalsIgnoreCase("DE"))
154
            		&& !(event.getPropertyId().toString().equalsIgnoreCase("Deutschland"))){
155
                final Item item = event.getItem();
156
                Property<?> itemProperty = item.getItemProperty("uuid");
157
                UUID uuid = UUID.fromString(itemProperty.getValue().toString());
158
                final Taxon taxon = CdmBase.deproxy(CdmSpringContextHelper.getTaxonService()
159
                		.load(uuid,Arrays.asList("descriptions.descriptionElements","name.taxonBases","updatedBy")), Taxon.class);
160
                final String areaID = (String)event.getPropertyId();
161
                PresenceAbsenceTerm presenceAbsenceTerm = null;
162
                Object statusValue = item.getItemProperty(areaID).getValue();
163
                if(statusValue instanceof String){
164
//                	presenceAbsenceTerm = TermCacher.getInstance().getPresenceAbsenceTerm((String) statusValue);
165
                    try {
166
                        presenceAbsenceTerm = (PresenceAbsenceTerm)CdmSpringContextHelper.getTermService().load(UUID.fromString((String)statusValue));
167
                    }catch(IllegalArgumentException|ClassCastException e) {
168
                        // Not a PresenceAbsenceTerm Column
169
                    }
170
                }
171
                //popup window
172
                final Window popup = new Window(Messages.getLocalizedString(Messages.DistributionTableViewBean_CHOOSE_DISTRIBUTION_STATUS));
173
                DelegatingErrorHandler errorHandler = new DelegatingErrorHandler();
174
                errorHandler.registerHandler(HibernateSystemException.class, new HibernateSystemErrorHandler());
175
                popup.setErrorHandler(errorHandler);
176
                final ListSelect termSelect = new ListSelect();
177
                termSelect.setSizeFull();
178
                termSelect.setContainerDataSource(getPresenter().getPresenceAbsenceTermContainer());
179
                termSelect.setNullSelectionAllowed(presenceAbsenceTerm != null);
180
                if(presenceAbsenceTerm != null){
181
                	termSelect.setNullSelectionItemId(Messages.getLocalizedString(Messages.DistributionTableViewBean_NO_STATUS_SELECT));
182
                }else{
183
                    logger.debug("No distribution status exists yet for area");
184
                }
185
                termSelect.setValue(presenceAbsenceTerm);
186
                termSelect.addValueChangeListener(valueChangeEvent -> {
187
						Object distributionStatus = valueChangeEvent.getProperty().getValue();
188
						getPresenter().updateDistributionField(areaID, distributionStatus, taxon);
189
						container.refresh();
190
						popup.close();
191
				});
192
                VerticalLayout layout = new VerticalLayout(termSelect);
193
                popup.setContent(layout);
194
                popup.setModal(true);
195
                popup.center();
196
                UI.getCurrent().addWindow(popup);
197
            }
198
        });
199

    
200
		mainLayout.addComponent(table, "top:75px;right:10.0px;left:10.0px;");
201

    
202
//		grid = new Grid();
203
//		grid.setSizeFull();
204
//		grid.setEditorEnabled(true);
205
//      grid.setFooterVisible(true);
206
//		mainLayout.addComponent(grid, "top:75px;right:10.0px;left:10.0px;"); //$NON-NLS-1$
207

    
208
		return mainLayout;
209
	}
210

    
211
    /**
212
     * {@inheritDoc}
213
     */
214
	@Override
215
	public void enter(ViewChangeEvent event) {
216
	    update();
217
	}
218

    
219
    /**
220
     * {@inheritDoc}
221
     */
222
	@Override
223
	public void update(){
224
		try {
225
			container = getPresenter().getSQLContainer();
226
		} catch (SQLException e) {
227
			DistributionEditorUtil.showSqlError(e);
228
			return;
229
		}
230
		if(container==null){
231
			return;
232
		}
233

    
234
		table.setContainerDataSource(container);
235

    
236
		List<String> columnHeaders = new ArrayList<>(Arrays.asList(table.getColumnHeaders()));
237
		columnHeaders.remove(CdmQueryFactory.DTYPE_COLUMN);
238
		columnHeaders.remove(CdmQueryFactory.ID_COLUMN);
239
		columnHeaders.remove(CdmQueryFactory.UUID_COLUMN);
240
		columnHeaders.remove(CdmQueryFactory.CLASSIFICATION_COLUMN);
241
//		columnHeaders.sort(new Comparator<String>() {
242
//            @Override
243
//            public int compare(String o1, String o2) {
244
//                if(o1.equals(CdmQueryFactory.TAXON_COLUMN) || o2.equals(CdmQueryFactory.TAXON_COLUMN)) {
245
//                    return o1.equals(CdmQueryFactory.TAXON_COLUMN) ? -1 : 1;
246
//                }
247
//                if(o1.equals(CdmQueryFactory.RANK_COLUMN) || o2.equals(CdmQueryFactory.RANK_COLUMN)) {
248
//                    return o1.equals(CdmQueryFactory.RANK_COLUMN) ? -1 : 1;
249
//                }
250
//
251
//                // TODO: HACK FOR RL 2017, REMOVE AS SOON AS POSSIBLE
252
//                if(o1.equals("DE") || o1.equals("Deutschland")
253
//                        || o2.equals("DE") || o2.equals("Deutschland")) {
254
//                    return (o1.equals("DE") || o1.equals("Deutschland")) ? -1 : 1;
255
//                }
256
//
257
//                return o1.compareTo(o2);
258
//            }
259
//		});
260

    
261
		List<String> columnList = new ArrayList<>(columnHeaders);
262

    
263
		String[] string = new String[columnList.size()];
264

    
265
		table.setVisibleColumns(columnList.toArray());
266
		table.setColumnHeaders(columnList.toArray(string));
267
		table.setColumnFooter(CdmQueryFactory.TAXON_COLUMN, String.format(Messages.getLocalizedString(Messages.DistributionTableViewBean_TOTAL_TAXA), container.size()));
268

    
269
//        gridcontainer = getPresenter().getAreaDistributionStatusContainer();
270
//        if(gridcontainer==null){
271
//            return;
272
//        }
273
//
274
//        if(footerRow != null) {
275
//            grid.removeFooterRow(footerRow);
276
//        }
277
//		grid.removeAllColumns();
278
//
279
//        grid.setContainerDataSource(gridcontainer);
280
//
281
//        Column uuidColumn = grid.getColumn(DistributionStatusQuery.UUID_COLUMN);
282
//        uuidColumn.setEditable(false);
283
//        uuidColumn.setHidden(true);
284
//        Column taxonColumn = grid.getColumn(DistributionStatusQuery.TAXON_COLUMN);
285
//        taxonColumn.setEditable(false);
286
//        taxonColumn.setHeaderCaption(Messages.DistributionTableViewBean_TAXON);
287
//        taxonColumn.setLastFrozenColumn();
288
//
289
//        Converter<String, UUID> displayConverter = new PresenceAbsenceTermUuidTitleStringConverter();
290
//        Converter<Object, UUID> editorConverter = new PresenceAbsenceTermUuidObjectConverter();
291
//        for(Column c : grid.getColumns()) {
292
//            if(c.isEditable()) {
293
//                NamedArea namedArea = (NamedArea) CdmSpringContextHelper.getTermService().load((UUID.fromString(c.getHeaderCaption())));
294
//                String caption = DistributionEditorUtil.isAbbreviatedLabels() ?
295
//                        namedArea.getRepresentation(Language.DEFAULT()).getAbbreviatedLabel() : namedArea.getTitleCache();
296
//                c.setHeaderCaption(caption);
297
//                c.setConverter(displayConverter);
298
//
299
//                NativeSelect termSelect = new NativeSelect();
300
//                termSelect.setSizeFull();
301
//                termSelect.setContainerDataSource(getPresenter().getPresenceAbsenceTermContainer());
302
//                termSelect.setItemCaptionMode(ItemCaptionMode.PROPERTY);
303
//                termSelect.setItemCaptionPropertyId("titleCache"); //$NON-NLS-1$
304
//                termSelect.setConverter(editorConverter);
305
//                termSelect.setImmediate(true);
306
//                c.setEditorField(termSelect);
307
//            }
308
//        }
309
//        grid.getEditorFieldGroup().addCommitHandler(new CommitHandler() {
310
//            private static final long serialVersionUID = 7515807188410712420L;
311
//
312
//            @Override
313
//            public void preCommit(CommitEvent commitEvent) throws CommitException {
314
//
315
//            }
316
//
317
//            @Override
318
//            public void postCommit(CommitEvent commitEvent) throws CommitException {
319
//                gridcontainer.commit();
320
//            }
321
//        });
322
//
323
//        footerRow = grid.appendFooterRow();
324
//        Object[] cells = grid.getColumns().stream().map(c -> c.getPropertyId()).toArray(Object[]::new);
325
//        if(cells.length == 0) {
326
//            return;
327
//        }
328
//        FooterCell footerCell = null;
329
//        if(cells.length > 1) {
330
//            footerCell = footerRow.join(cells);
331
//        }else {
332
//            footerCell = footerRow.getCell(cells[0]);
333
//        }
334
//        footerCell.setText(String.format(Messages.DistributionTableViewBean_TOTAL_TAXA, gridcontainer.size()));
335
	}
336

    
337
	private void createEditClickListener(){
338
		//details
339
	    Button detailButton = toolbar.getDetailButton();
340
		detailButton.setCaption(Messages.getLocalizedString(Messages.DistributionTableViewBean_TAXON_DETAILS));
341
		detailButton.addClickListener(event -> {
342
				Object selectedItemId = DistributionTableViewBean.this.table.getValue();
343
//				Object selectedItemId = DistributionTableViewBean.this.grid.getSelectedRow();
344
				if(selectedItemId!=null){
345
				    final UUID uuid = UUID.fromString(table.getContainerDataSource().getItem(selectedItemId).getItemProperty("uuid").getValue().toString());
346
//					final UUID uuid = (UUID) selectedItemId;
347
					Taxon taxon = HibernateProxyHelper.deproxy(CdmSpringContextHelper.getTaxonService().load(uuid), Taxon.class);
348
//					Taxon taxon = (Taxon) CdmSpringContextHelper.getTaxonService().load(uuid);
349
					List<DescriptionElementBase> listDescriptions = getPresenter().listDescriptionElementsForTaxon(taxon, null);
350
					DetailWindow detailWindow = new DetailWindow(taxon, listDescriptions);
351
					Window window = detailWindow.createWindow();
352
					window.center();
353
					getUI().addWindow(window);
354
				}
355
				else{
356
					Notification.show(Messages.getLocalizedString(Messages.DistributionTableViewBean_SELECT_TAXON), Type.HUMANIZED_MESSAGE);
357
				}
358
			}
359
		);
360

    
361
		//area and taxon
362
		Button areaAndTaxonSettingsButton = toolbar.getDistributionSettingsButton();
363
		areaAndTaxonSettingsButton.addClickListener(event -> openAreaAndTaxonSettings());
364

    
365
		//distr status
366
		Button distrStatusButton = toolbar.getSettingsButton();
367
		distrStatusButton.addClickListener(event -> openStatusSettings());
368
	}
369

    
370
    /**
371
     * {@inheritDoc}
372
     */
373
	@Override
374
	public void openStatusSettings() {
375
        if(distributionStatusConfigWindow==null){
376
            distributionStatusConfigWindow = new DistributionStatusSettingsConfigWindow(this);
377
        }
378
        Window window  = distributionStatusConfigWindow.createWindow(Messages.getLocalizedString(Messages.DistributionTableViewBean_STATUS));
379
        window.setWidth("25%"); //$NON-NLS-1$
380
        window.setHeight("60%"); //$NON-NLS-1$
381
        UI.getCurrent().addWindow(window);
382
	}
383

    
384
    /**
385
     * {@inheritDoc}
386
     */
387
	@Override
388
	public void openAreaAndTaxonSettings() {
389
		if(areaAndTaxonConfigWindow==null){
390
			areaAndTaxonConfigWindow = new AreaAndTaxonSettingsConfigWindow(this);
391
		}
392
        Window window  = areaAndTaxonConfigWindow.createWindow(Messages.getLocalizedString(Messages.DistributionTableViewBean_AREAS_AND_TAXA));
393
        UI.getCurrent().addWindow(window);
394
	}
395

    
396
    /**
397
     * {@inheritDoc}
398
     */
399
	@Override
400
	public boolean allowAnonymousAccess() {
401
		// TODO Auto-generated method stub
402
		return false;
403
	}
404

    
405
    /**
406
     * {@inheritDoc}
407
     */
408
	@Override
409
	public Collection<Collection<GrantedAuthority>> allowedGrantedAuthorities() {
410
		// TODO Auto-generated method stub
411
		return null;
412
	}
413

    
414
    /**
415
     * {@inheritDoc}
416
     */
417
	@Override
418
	protected String getHeaderText() {
419
		// TODO Auto-generated method stub
420
		return null;
421
	}
422

    
423
    /**
424
     * {@inheritDoc}
425
     */
426
	@Override
427
	protected String getSubHeaderText() {
428
		// TODO Auto-generated method stub
429
		return null;
430
	}
431

    
432
    /**
433
     * {@inheritDoc}
434
     */
435
	@Override
436
	protected void initContent() {
437
	    // initialize layout
438
        AbsoluteLayout mainLayout = initLayout();
439
        setCompositionRoot(mainLayout);
440
        // add click listener on DistributionToolbar-buttons
441
        createEditClickListener();
442
	}
443
}
(4-4/7)