Project

General

Profile

Download (19.4 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.name;
10

    
11
import java.util.Arrays;
12
import java.util.EnumSet;
13
import java.util.HashMap;
14
import java.util.HashSet;
15
import java.util.Map;
16
import java.util.Set;
17
import java.util.Stack;
18

    
19
import org.springframework.beans.factory.DisposableBean;
20
import org.springframework.beans.factory.annotation.Autowired;
21
import org.springframework.context.annotation.Scope;
22
import org.vaadin.spring.events.annotation.EventBusListenerMethod;
23
import org.vaadin.viritin.fields.AbstractElementCollection;
24

    
25
import com.vaadin.spring.annotation.SpringComponent;
26

    
27
import eu.etaxonomy.cdm.cache.CdmTransientEntityAndUuidCacher;
28
import eu.etaxonomy.cdm.format.ReferenceEllypsisFormatter.LabelType;
29
import eu.etaxonomy.cdm.model.ICdmEntityUuidCacher;
30
import eu.etaxonomy.cdm.model.agent.AgentBase;
31
import eu.etaxonomy.cdm.model.agent.Person;
32
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
33
import eu.etaxonomy.cdm.model.common.CdmBase;
34
import eu.etaxonomy.cdm.model.location.Country;
35
import eu.etaxonomy.cdm.model.name.Registration;
36
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
37
import eu.etaxonomy.cdm.model.occurrence.Collection;
38
import eu.etaxonomy.cdm.model.reference.Reference;
39
import eu.etaxonomy.cdm.model.term.TermType;
40
import eu.etaxonomy.cdm.persistence.dao.common.Restriction;
41
import eu.etaxonomy.cdm.persistence.dao.common.Restriction.Operator;
42
import eu.etaxonomy.cdm.persistence.hibernate.permission.CRUD;
43
import eu.etaxonomy.cdm.persistence.query.MatchMode;
44
import eu.etaxonomy.cdm.service.CdmBeanItemContainerFactory;
45
import eu.etaxonomy.cdm.service.CdmFilterablePagingProvider;
46
import eu.etaxonomy.cdm.service.CdmFilterablePagingProviderFactory;
47
import eu.etaxonomy.cdm.service.ISpecimenTypeDesignationWorkingSetService;
48
import eu.etaxonomy.cdm.service.UserHelperAccess;
49
import eu.etaxonomy.cdm.service.initstrategies.AgentBaseInit;
50
import eu.etaxonomy.cdm.vaadin.component.CollectionRowItemCollection;
51
import eu.etaxonomy.cdm.vaadin.event.EditorActionContext;
52
import eu.etaxonomy.cdm.vaadin.event.EntityChangeEvent;
53
import eu.etaxonomy.cdm.vaadin.event.EntityChangeEventFilter;
54
import eu.etaxonomy.cdm.vaadin.event.ToOneRelatedEntityReloader;
55
import eu.etaxonomy.cdm.vaadin.model.registration.RegistrationTermLists;
56
import eu.etaxonomy.cdm.vaadin.model.registration.SpecimenTypeDesignationDTO;
57
import eu.etaxonomy.cdm.vaadin.model.registration.SpecimenTypeDesignationWorkingSetDTO;
58
import eu.etaxonomy.cdm.vaadin.ui.RegistrationUIDefaults;
59
import eu.etaxonomy.cdm.vaadin.util.CollectionCaptionGenerator;
60
import eu.etaxonomy.cdm.vaadin.util.ReferenceEllypsisCaptionGenerator;
61
import eu.etaxonomy.cdm.vaadin.view.occurrence.CollectionPopupEditor;
62
import eu.etaxonomy.cdm.vaadin.view.reference.ReferencePopupEditor;
63
import eu.etaxonomy.vaadin.component.ToOneRelatedEntityCombobox;
64
import eu.etaxonomy.vaadin.mvp.AbstractEditorPresenter;
65
import eu.etaxonomy.vaadin.mvp.AbstractPopupEditor;
66
import eu.etaxonomy.vaadin.mvp.AbstractView;
67
/**
68
 * SpecimenTypeDesignationWorkingsetPopupEditorView implementation must override the showInEditor() method,
69
 * see {@link #prepareAsFieldGroupDataSource()} for details.
70
 *
71
 * @author a.kohlbecker
72
 * @since Jun 13, 2017
73
 *
74
 */
75
@SpringComponent
76
@Scope("prototype")
77
public class SpecimenTypeDesignationWorkingsetEditorPresenter
78
    extends AbstractEditorPresenter<SpecimenTypeDesignationWorkingSetDTO , SpecimenTypeDesignationWorkingsetPopupEditorView>
79
    implements CachingPresenter, DisposableBean {
80

    
81
    private static final long serialVersionUID = 4255636253714476918L;
82

    
83
    private static final EnumSet<CRUD> COLLECTION_EDITOR_CRUD = EnumSet.of(CRUD.UPDATE, CRUD.DELETE);
84

    
85

    
86
    /**
87
     * This object for this field will either be injected by the {@link PopupEditorFactory} or by a Spring
88
     * {@link BeanFactory}
89
     */
90
    @Autowired
91
    private ISpecimenTypeDesignationWorkingSetService specimenTypeDesignationWorkingSetService;
92

    
93
    @Autowired
94
    protected CdmFilterablePagingProviderFactory pagingProviderFactory;
95

    
96
    @Autowired
97
    protected CdmBeanItemContainerFactory cdmBeanItemContainerFactory;
98

    
99
    /**
100
     * if not null, this CRUD set is to be used to create a CdmAuthoritiy for the base entitiy which will be
101
     * granted to the current use as long this grant is not assigned yet.
102
     */
103
    private EnumSet<CRUD> crud = null;
104

    
105
    private ICdmEntityUuidCacher cache;
106

    
107
    SpecimenTypeDesignationWorkingSetDTO<Registration> workingSetDto;
108

    
109
    private Map<CollectionPopupEditor, SpecimenTypeDesignationDTORow> collectionPopupEditorsRowMap = new HashMap<>();
110

    
111
    private Map<ReferencePopupEditor, SpecimenTypeDesignationDTORow> referencePopupEditorsRowMap = new HashMap<>();
112

    
113
    private Set<CollectionRowItemCollection> popuEditorTypeDesignationSourceRows = new HashSet<>();
114

    
115
    private java.util.Collection<CdmBase> rootEntities = new HashSet<>();
116

    
117

    
118
    /**
119
     * Loads an existing working set from the database. This process actually involves
120
     * loading the Registration specified by the <code>RegistrationAndWorkingsetId.registrationId</code> and in
121
     * a second step to find the workingset by the <code>registrationAndWorkingsetId.workingsetId</code>.
122
     * <p>
123
     * The <code>identifier</code> must be of the type {@link TypeDesignationWorkingsetEditorIdSet} whereas the field <code>egistrationId</code>
124
     * must be present, the field <code>workingsetId</code>,  however can be null. I this case a new workingset with a new {@link FieldUnit} as
125
     * base entity is being created.
126
     *
127
     * @param identifier a {@link TypeDesignationWorkingsetEditorIdSet}
128
     */
129
    @Override
130
    protected SpecimenTypeDesignationWorkingSetDTO<Registration> loadBeanById(Object identifier) {
131

    
132
        cache = new CdmTransientEntityAndUuidCacher(this);
133
        if(identifier != null){
134

    
135
            TypeDesignationWorkingsetEditorIdSet idset = (TypeDesignationWorkingsetEditorIdSet)identifier;
136

    
137
            if(idset.baseEntityRef != null){
138
                workingSetDto = specimenTypeDesignationWorkingSetService.load(idset.registrationUuid, idset.baseEntityRef);
139
                if(workingSetDto.getFieldUnit() == null){
140
                    workingSetDto = specimenTypeDesignationWorkingSetService.fixMissingFieldUnit(workingSetDto);
141
                        // FIXME open Dialog to warn user about adding an empty fieldUnit to the typeDesignations
142
                        //       This method must go again into the presenter !!!!
143
                        logger.info("Basing all typeDesignations on a new fieldUnit");
144
                }
145
                // need to use load but put see #7214
146
                cache.load(workingSetDto.getOwner());
147
                rootEntities.add(workingSetDto.getOwner());
148
            } else {
149
                // create a new workingset, for a new fieldunit which is the base for the workingset
150
                workingSetDto = specimenTypeDesignationWorkingSetService.create(idset.registrationUuid, idset.publicationUuid, idset.typifiedNameUuid);
151
                // need to use load but put see #7214
152
                Registration registration = workingSetDto.getOwner();
153
                cache.load(registration);
154
                if(registration.getName() == null && (registration.getTypeDesignations() == null || registration.getTypeDesignations().isEmpty())){
155
                    // need to add the citation to the cache when there is no name or typedesignation in the registry which would bring the citation otherwise.
156
                    cache.load(workingSetDto.getCitation());
157
                }
158
                cache.load(workingSetDto.getTypifiedName());
159
                rootEntities.add(workingSetDto.getOwner());
160
                rootEntities.add(workingSetDto.getTypifiedName());
161
                rootEntities.add(workingSetDto.getCitation());
162
            }
163

    
164
        } else {
165
            workingSetDto = null;
166
        }
167

    
168
        return workingSetDto;
169
    }
170

    
171

    
172
    /**
173
     * {@inheritDoc}
174
     */
175
    @SuppressWarnings("serial")
176
    @Override
177
    public void handleViewEntered() {
178

    
179
        getView().getCountrySelectField().setContainerDataSource(cdmBeanItemContainerFactory.buildBeanItemContainer(Country.uuidCountryVocabulary));
180

    
181
        CdmFilterablePagingProvider<AgentBase, TeamOrPersonBase> termOrPersonPagingProvider = new CdmFilterablePagingProvider<AgentBase, TeamOrPersonBase>(getRepo().getAgentService(), TeamOrPersonBase.class);
182
        CdmFilterablePagingProvider<AgentBase, Person> personPagingProvider = new CdmFilterablePagingProvider<AgentBase, Person>(getRepo().getAgentService(), Person.class);
183
        termOrPersonPagingProvider.setInitStrategy(AgentBaseInit.TEAM_OR_PERSON_INIT_STRATEGY);
184
        // the ToOneRelatedEntityReloader is added internally in the TeamOrPersonField:
185
        getView().getCollectorField().setFilterablePersonPagingProvider(personPagingProvider, this);
186
        getView().getCollectorField().setFilterableTeamPagingProvider(termOrPersonPagingProvider, this);
187

    
188
        getView().getExactLocationField().getReferenceSystemSelect().setContainerDataSource(cdmBeanItemContainerFactory.buildBeanItemContainer(TermType.ReferenceSystem));
189
        getView().getExactLocationField().getReferenceSystemSelect().setItemCaptionPropertyId("label");
190

    
191
        getView().getTypeDesignationsCollectionField().addElementRemovedListener(e -> deleteTypeDesignation(e.getElement()));
192
        getView().getTypeDesignationsCollectionField().addElementAddedListener(e -> addTypeDesignation(e.getElement()));
193

    
194
        popuEditorTypeDesignationSourceRows.clear();
195
        CdmFilterablePagingProvider<Collection, Collection> collectionPagingProvider = new CdmFilterablePagingProvider<Collection, Collection>(getRepo().getCollectionService());
196
        collectionPagingProvider.getRestrictions().add(new Restriction<>("institute.titleCache", Operator.OR, MatchMode.ANYWHERE, CdmFilterablePagingProvider.QUERY_STRING_PLACEHOLDER));
197

    
198
        CdmFilterablePagingProvider<Reference, Reference> referencePagingProvider = pagingProviderFactory.referencePagingProvider();
199

    
200
        getView().getTypeDesignationsCollectionField().setEditorInstantiator(new AbstractElementCollection.Instantiator<SpecimenTypeDesignationDTORow>() {
201

    
202
            @Override
203
            public SpecimenTypeDesignationDTORow create() {
204

    
205
                SpecimenTypeDesignationDTORow row = new SpecimenTypeDesignationDTORow();
206

    
207
                row.kindOfUnit.setContainerDataSource(cdmBeanItemContainerFactory.buildTermItemContainer(
208
                        RegistrationTermLists.KIND_OF_UNIT_TERM_UUIDS())
209
                        );
210
                row.kindOfUnit.setNullSelectionAllowed(false);
211

    
212
                row.typeStatus.setContainerDataSource(cdmBeanItemContainerFactory.buildTermItemContainer(
213
                        RegistrationTermLists.SPECIMEN_TYPE_DESIGNATION_STATUS_UUIDS())
214
                        );
215
                row.typeStatus.setNullSelectionAllowed(false);
216

    
217

    
218
                row.collection.loadFrom(
219
                        collectionPagingProvider,
220
                        collectionPagingProvider,
221
                        collectionPagingProvider.getPageSize()
222
                        );
223
                row.collection.getSelect().setCaptionGenerator(new CollectionCaptionGenerator());
224
                row.collection.getSelect().addValueChangeListener(new ToOneRelatedEntityReloader<Collection>(row.collection.getSelect(),
225
                        SpecimenTypeDesignationWorkingsetEditorPresenter.this));
226
                row.collection.addClickListenerAddEntity(e -> doCollectionEditorAdd(row));
227
                row.collection.addClickListenerEditEntity(e -> {
228
                        if(row.collection.getValue() != null){
229
                            doCollectionEditorEdit(row);
230
                        }
231
                    });
232

    
233
                row.mediaSpecimenReference.loadFrom(
234
                        referencePagingProvider,
235
                        referencePagingProvider,
236
                        collectionPagingProvider.getPageSize()
237
                        );
238

    
239
                row.mediaSpecimenReference.getSelect().setCaptionGenerator(new ReferenceEllypsisCaptionGenerator(LabelType.BIBLIOGRAPHIC, row.mediaSpecimenReference.getSelect()));
240
                row.mediaSpecimenReference.getSelect().addValueChangeListener(new ToOneRelatedEntityReloader<Reference>(row.mediaSpecimenReference.getSelect(),
241
                        SpecimenTypeDesignationWorkingsetEditorPresenter.this));
242
                row.mediaSpecimenReference.addClickListenerAddEntity(e -> doReferenceEditorAdd(row));
243
                row.mediaSpecimenReference.addClickListenerEditEntity(e -> {
244
                    if(row.mediaSpecimenReference.getValue() != null){
245
                        doReferenceEditorEdit(row);
246
                    }
247
                });
248

    
249
                getView().applyDefaultComponentStyle(row.components());
250

    
251
                popuEditorTypeDesignationSourceRows.add(row);
252

    
253
                return row;
254
            }
255

    
256
        });
257

    
258
    }
259

    
260

    
261
    /**
262
     * {@inheritDoc}
263
     */
264
    @Override
265
    protected void saveBean(SpecimenTypeDesignationWorkingSetDTO dto) {
266

    
267
        if(crud != null){
268
            UserHelperAccess.userHelper().createAuthorityForCurrentUser(dto.getFieldUnit(), crud, null);
269
        }
270

    
271
        specimenTypeDesignationWorkingSetService.save(dto);
272
    }
273

    
274
    /**
275
     * {@inheritDoc}
276
     */
277
    @Override
278
    protected void deleteBean(SpecimenTypeDesignationWorkingSetDTO bean) {
279
        specimenTypeDesignationWorkingSetService.delete(bean, true);
280
    }
281

    
282
    /**
283
     * @param element
284
     * @return
285
     */
286
    private void addTypeDesignation(SpecimenTypeDesignationDTO element) {
287
        getView().updateAllowDelete();
288
    }
289

    
290

    
291
    /**
292
     * In this method the SpecimenTypeDesignation is dissociated from the Registration.
293
     * The actual deletion of the SpecimenTypeDesignation and DerivedUnit will take place in {@link #saveBean(SpecimenTypeDesignationWorkingSetDTO)}
294
     *
295
     * TODO once https://dev.e-taxonomy.eu/redmine/issues/7077 is fixed dissociating from the Registration could be removed here
296
     *
297
     * @param e
298
     * @return
299
     */
300
    private void deleteTypeDesignation(SpecimenTypeDesignationDTO element) {
301

    
302
        Registration reg = workingSetDto.getOwner();
303
        SpecimenTypeDesignation std = element.asSpecimenTypeDesignation();
304

    
305
        reg.getTypeDesignations().remove(std);
306

    
307
        getView().updateAllowDelete();
308
    }
309

    
310
    /**
311
     * @param crud
312
     */
313
    public void setGrantsForCurrentUser(EnumSet<CRUD> crud) {
314
        this.crud = crud;
315

    
316
    }
317

    
318
    /**
319
     * {@inheritDoc}
320
     */
321
    @Override
322
    public ICdmEntityUuidCacher getCache() {
323
        return cache;
324
    }
325

    
326
    @Override
327
    public void disposeCache() {
328
        cache.dispose();
329
    }
330

    
331
    public void doCollectionEditorAdd(SpecimenTypeDesignationDTORow row) {
332

    
333
        CollectionPopupEditor collectionPopupEditor = openPopupEditor(CollectionPopupEditor.class, null);
334

    
335
        collectionPopupEditor.grantToCurrentUser(COLLECTION_EDITOR_CRUD);
336
        collectionPopupEditor.withDeleteButton(true);
337
        collectionPopupEditor.loadInEditor(null);
338

    
339
        collectionPopupEditorsRowMap.put(collectionPopupEditor, row);
340
    }
341

    
342
    public void doCollectionEditorEdit(SpecimenTypeDesignationDTORow row) {
343

    
344
        CollectionPopupEditor collectionPopupEditor = openPopupEditor(CollectionPopupEditor.class, null);
345

    
346
        collectionPopupEditor.grantToCurrentUser(COLLECTION_EDITOR_CRUD);
347
        collectionPopupEditor.withDeleteButton(true);
348
        collectionPopupEditor.loadInEditor(row.collection.getValue().getUuid());
349

    
350
        collectionPopupEditorsRowMap.put(collectionPopupEditor, row);
351
    }
352

    
353

    
354
    @EventBusListenerMethod(filter = EntityChangeEventFilter.OccurrenceCollectionFilter.class)
355
    public void onCollectionEvent(EntityChangeEvent event){
356

    
357
        if(event.getSourceView() instanceof AbstractPopupEditor) {
358

    
359
            Stack<EditorActionContext> context = ((AbstractPopupEditor) event.getSourceView()).getEditorActionContext();
360
            if(context.size() > 1){
361
               AbstractView<?> parentView = context.get(context.size() - 2).getParentView();
362
               if(getView().equals(parentView)){
363
                   Collection newCollection = getRepo().getCollectionService().load(
364
                           event.getEntityUuid(), Arrays.asList(new String[]{"$.institute"})
365
                           );
366
                   cache.load(newCollection);
367

    
368
                   if(event.isCreatedType()){
369
                       SpecimenTypeDesignationDTORow row = collectionPopupEditorsRowMap.get(event.getSourceView());
370
                       ToOneRelatedEntityCombobox<Collection> combobox = row.getComponent(ToOneRelatedEntityCombobox.class, 3);
371
                       combobox.setValue((Collection) event.getEntity());
372
                   }
373
                   for( CollectionRowItemCollection row : popuEditorTypeDesignationSourceRows) {
374
                       ToOneRelatedEntityCombobox<Collection> combobox = row.getComponent(ToOneRelatedEntityCombobox.class, 3);
375
                       combobox.reload();
376
                   }
377
               }
378
            }
379

    
380
        }
381
    }
382

    
383
    public void doReferenceEditorAdd(SpecimenTypeDesignationDTORow row) {
384

    
385
        ReferencePopupEditor referencePopupEditor = openPopupEditor(ReferencePopupEditor.class, null);
386

    
387
        referencePopupEditor.withReferenceTypes(RegistrationUIDefaults.MEDIA_REFERENCE_TYPES);
388
        referencePopupEditor.grantToCurrentUser(COLLECTION_EDITOR_CRUD);
389
        referencePopupEditor.withDeleteButton(true);
390
        referencePopupEditor.loadInEditor(null);
391

    
392
        referencePopupEditorsRowMap.put(referencePopupEditor, row);
393
    }
394

    
395
    public void doReferenceEditorEdit(SpecimenTypeDesignationDTORow row) {
396

    
397
        ReferencePopupEditor referencePopupEditor = openPopupEditor(ReferencePopupEditor.class, null);
398
        referencePopupEditor.withReferenceTypes(RegistrationUIDefaults.MEDIA_REFERENCE_TYPES);
399
        referencePopupEditor.grantToCurrentUser(COLLECTION_EDITOR_CRUD);
400
        referencePopupEditor.withDeleteButton(true);
401
        referencePopupEditor.loadInEditor(row.mediaSpecimenReference.getValue().getUuid());
402

    
403
        referencePopupEditorsRowMap.put(referencePopupEditor, row);
404
    }
405

    
406
    @EventBusListenerMethod(filter = EntityChangeEventFilter.ReferenceFilter.class)
407
    public void onReferenceEvent(EntityChangeEvent event){
408

    
409
        Reference newRef = getRepo().getReferenceService().load(event.getEntityUuid(), Arrays.asList(new String[]{"$"}));
410
        cache.load(newRef);
411

    
412
        if(event.isCreatedType()){
413
            SpecimenTypeDesignationDTORow row = referencePopupEditorsRowMap.get(event.getSourceView());
414
            ToOneRelatedEntityCombobox<Reference> combobox = row.getComponent(ToOneRelatedEntityCombobox.class, 7);
415
            combobox.setValue((Reference) event.getEntity());
416

    
417
        } else {
418
            for( CollectionRowItemCollection row : popuEditorTypeDesignationSourceRows) {
419
                ToOneRelatedEntityCombobox<Reference> combobox = row.getComponent(ToOneRelatedEntityCombobox.class, 7);
420
                combobox.reload();
421
            }
422
        }
423
    }
424

    
425
    /**
426
     * {@inheritDoc}
427
     */
428
    @Override
429
    public void addRootEntity(CdmBase entity) {
430
        rootEntities.add(entity);
431
    }
432

    
433
    /**
434
     * {@inheritDoc}
435
     */
436
    @Override
437
    public java.util.Collection<CdmBase> getRootEntities() {
438
        return rootEntities ;
439
    }
440

    
441
    /**
442
     * {@inheritDoc}
443
     */
444
    @Override
445
    public void destroy() throws Exception {
446
        super.destroy();
447
        cache.dispose();
448
    }
449

    
450
}
(7-7/14)