Project

General

Profile

Download (30.7 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.registration;
10

    
11
import java.util.ArrayList;
12
import java.util.Arrays;
13
import java.util.EnumSet;
14
import java.util.List;
15
import java.util.Set;
16
import java.util.Stack;
17
import java.util.UUID;
18

    
19
import org.hibernate.Session;
20
import org.hibernate.Transaction;
21
import org.springframework.beans.factory.annotation.Autowired;
22
import org.springframework.security.core.Authentication;
23
import org.springframework.transaction.TransactionStatus;
24
import org.vaadin.spring.events.annotation.EventBusListenerMethod;
25

    
26
import com.vaadin.server.SystemError;
27
import com.vaadin.spring.annotation.SpringComponent;
28
import com.vaadin.spring.annotation.ViewScope;
29
import com.vaadin.ui.Button;
30
import com.vaadin.ui.Label;
31
import com.vaadin.ui.UI;
32
import com.vaadin.ui.VerticalLayout;
33
import com.vaadin.ui.Window;
34

    
35
import eu.etaxonomy.cdm.api.service.INameService;
36
import eu.etaxonomy.cdm.api.service.IRegistrationService;
37
import eu.etaxonomy.cdm.api.service.dto.EntityReference;
38
import eu.etaxonomy.cdm.api.service.dto.RegistrationDTO;
39
import eu.etaxonomy.cdm.api.service.dto.TypedEntityReference;
40
import eu.etaxonomy.cdm.api.service.exception.RegistrationValidationException;
41
import eu.etaxonomy.cdm.api.service.idminter.IdentifierMinter.Identifier;
42
import eu.etaxonomy.cdm.api.service.idminter.RegistrationIdentifierMinter;
43
import eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager.TypeDesignationWorkingSetType;
44
import eu.etaxonomy.cdm.ext.common.ExternalServiceException;
45
import eu.etaxonomy.cdm.ext.registration.messages.IRegistrationMessageService;
46
import eu.etaxonomy.cdm.model.common.User;
47
import eu.etaxonomy.cdm.model.name.NameTypeDesignation;
48
import eu.etaxonomy.cdm.model.name.Rank;
49
import eu.etaxonomy.cdm.model.name.Registration;
50
import eu.etaxonomy.cdm.model.name.RegistrationStatus;
51
import eu.etaxonomy.cdm.model.name.TaxonName;
52
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
53
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
54
import eu.etaxonomy.cdm.model.reference.Reference;
55
import eu.etaxonomy.cdm.persistence.hibernate.permission.CRUD;
56
import eu.etaxonomy.cdm.persistence.hibernate.permission.Operation;
57
import eu.etaxonomy.cdm.service.CdmFilterablePagingProvider;
58
import eu.etaxonomy.cdm.service.CdmStore;
59
import eu.etaxonomy.cdm.service.IRegistrationWorkingSetService;
60
import eu.etaxonomy.cdm.vaadin.component.registration.RegistrationItem;
61
import eu.etaxonomy.cdm.vaadin.event.AbstractEditorAction.EditorActionContext;
62
import eu.etaxonomy.cdm.vaadin.event.EditorActionTypeFilter;
63
import eu.etaxonomy.cdm.vaadin.event.EntityChangeEvent;
64
import eu.etaxonomy.cdm.vaadin.event.ReferenceEditorAction;
65
import eu.etaxonomy.cdm.vaadin.event.RegistrationEditorAction;
66
import eu.etaxonomy.cdm.vaadin.event.ShowDetailsEvent;
67
import eu.etaxonomy.cdm.vaadin.event.ShowDetailsEventEntityTypeFilter;
68
import eu.etaxonomy.cdm.vaadin.event.TaxonNameEditorAction;
69
import eu.etaxonomy.cdm.vaadin.event.TypeDesignationWorkingsetEditorAction;
70
import eu.etaxonomy.cdm.vaadin.event.registration.RegistrationWorkingsetAction;
71
import eu.etaxonomy.cdm.vaadin.model.registration.RegistrationWorkingSet;
72
import eu.etaxonomy.cdm.vaadin.permission.UserHelper;
73
import eu.etaxonomy.cdm.vaadin.theme.EditValoTheme;
74
import eu.etaxonomy.cdm.vaadin.ui.RegistrationUIDefaults;
75
import eu.etaxonomy.cdm.vaadin.util.CdmTitleCacheCaptionGenerator;
76
import eu.etaxonomy.cdm.vaadin.view.name.NameTypeDesignationPopupEditor;
77
import eu.etaxonomy.cdm.vaadin.view.name.SpecimenTypeDesignationWorkingsetPopupEditor;
78
import eu.etaxonomy.cdm.vaadin.view.name.TaxonNamePopupEditor;
79
import eu.etaxonomy.cdm.vaadin.view.name.TaxonNamePopupEditorMode;
80
import eu.etaxonomy.cdm.vaadin.view.name.TaxonNamePopupEditorView;
81
import eu.etaxonomy.cdm.vaadin.view.name.TypeDesignationWorkingsetEditorIdSet;
82
import eu.etaxonomy.cdm.vaadin.view.reference.ReferencePopupEditor;
83
import eu.etaxonomy.vaadin.mvp.AbstractPopupEditor;
84
import eu.etaxonomy.vaadin.mvp.AbstractPresenter;
85
import eu.etaxonomy.vaadin.mvp.AbstractView;
86
import eu.etaxonomy.vaadin.mvp.BeanInstantiator;
87
import eu.etaxonomy.vaadin.ui.view.DoneWithPopupEvent;
88
import eu.etaxonomy.vaadin.ui.view.DoneWithPopupEvent.Reason;
89

    
90
/**
91
 * @author a.kohlbecker
92
 * @since Mar 3, 2017
93
 *
94
 */
95
@SpringComponent
96
@ViewScope
97
public class RegistrationWorkingsetPresenter extends AbstractPresenter<RegistrationWorkingsetView> {
98

    
99
    /**
100
     *
101
     */
102
    private static final List<String> REGISTRATION_INIT_STRATEGY = Arrays.asList(
103
            "$",
104
            "blockedBy",
105
            "name.combinationAuthorship",
106
            "name.exCombinationAuthorship",
107
            "name.basionymAuthorship",
108
            "name.exBasionymAuthorship"
109
            );
110

    
111
    private static final long serialVersionUID = 1L;
112

    
113
    @Autowired
114
    private IRegistrationWorkingSetService regWorkingSetService;
115

    
116
    @Autowired
117
    private RegistrationIdentifierMinter minter;
118

    
119
    @Autowired
120
    private IRegistrationMessageService messageService;
121

    
122
    /**
123
     * @return the regWorkingSetService
124
     */
125
    public IRegistrationWorkingSetService getWorkingSetService() {
126
        return regWorkingSetService;
127
    }
128

    
129
    private RegistrationWorkingSet workingset;
130

    
131
    private TaxonName newTaxonNameForRegistration = null;
132

    
133
    private RegistrationDTO newRegistrationDTOWithExistingName;
134

    
135
    private RegistrationDTO newNameTypeDesignationTarget;
136

    
137

    
138
    /**
139
     *
140
     */
141
    public RegistrationWorkingsetPresenter() {
142
    }
143

    
144
    /**
145
     * Always create a new Store
146
     *
147
     * @return
148
     */
149
    protected CdmStore<Registration, IRegistrationService> getRegistrationStore(){
150
        return new CdmStore<Registration, IRegistrationService>(getRepo(), getRepo().getRegistrationService());
151
    }
152

    
153
    /**
154
     * Always create a new Store
155
     *
156
     * @return
157
     */
158
    protected CdmStore<TaxonName, INameService> getTaxonNameStore(){
159
        return new  CdmStore<TaxonName, INameService>(getRepo(), getRepo().getNameService());
160
    }
161

    
162

    
163
    /**
164
     * @param taxonNameId
165
     * @return
166
     */
167
    protected Registration createNewRegistrationForName(UUID taxonNameUuid) {
168
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
169
        // move into RegistrationWorkflowStateMachine
170
        TransactionStatus txStatus = getRepo().startTransaction();
171

    
172
        Identifier<String> identifiers = minter.mint();
173
        if(identifiers.getIdentifier() == null){
174
            throw new RuntimeException("RegistrationIdentifierMinter configuration incomplete.");
175
        }
176
        Registration reg = Registration.NewInstance(
177
                identifiers.getIdentifier(),
178
                identifiers.getLocalId(),
179
                taxonNameUuid != null ? getRepo().getNameService().find(taxonNameUuid) : null,
180
                null);
181
        Authentication authentication = currentSecurityContext().getAuthentication();
182
        reg.setSubmitter((User)authentication.getPrincipal());
183
        EntityChangeEvent event = getRegistrationStore().saveBean(reg, (AbstractView) getView());
184
        UserHelper.fromSession().createAuthorityForCurrentUser(Registration.class, event.getEntityUuid(), Operation.UPDATE, RegistrationStatus.PREPARATION.name());
185
        getRepo().commitTransaction(txStatus);
186
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
187
        return getRepo().getRegistrationService().load(event.getEntityUuid(), Arrays.asList(new String []{"blockedBy"}));
188
    }
189

    
190

    
191
    /**
192
     * @param doReload TODO
193
     *
194
     */
195
    protected void refreshView(boolean doReload) {
196
        if(workingset == null){
197
            return; // nothing to do
198
        }
199
        if(doReload){
200
            loadWorkingSet(workingset.getCitationUuid());
201
        }
202
        getView().setWorkingset(workingset);
203
    }
204

    
205

    
206
    /**
207
     * {@inheritDoc}
208
     */
209
    @Override
210
    public void handleViewEntered() {
211

    
212
        super.handleViewEntered();
213

    
214
        loadWorkingSet(getView().getCitationUuid());
215
        getView().setWorkingset(workingset);
216

    
217
        // PagingProviders and CacheGenerator for the existingNameCombobox
218
        CdmFilterablePagingProvider<TaxonName, TaxonName> pagingProvider = new CdmFilterablePagingProvider<TaxonName, TaxonName>(
219
                getRepo().getNameService());
220
        CdmTitleCacheCaptionGenerator<TaxonName> titleCacheGenerator = new CdmTitleCacheCaptionGenerator<TaxonName>();
221
        getView().getAddExistingNameCombobox().setCaptionGenerator(titleCacheGenerator);
222
        getView().getAddExistingNameCombobox().loadFrom(pagingProvider, pagingProvider, pagingProvider.getPageSize());
223

    
224
        // update the messages
225
        User user = UserHelper.fromSession().user();
226
        for (UUID registrationUuid : getView().getRegistrationItemMap().keySet()) {
227
            Button messageButton = getView().getRegistrationItemMap().get(registrationUuid).regItemButtons.getMessagesButton();
228

    
229
            RegistrationDTO regDto = workingset.getRegistrationDTO(registrationUuid).get();
230
            try {
231
                int messageCount = messageService.countActiveMessagesFor(regDto.registration(), user);
232

    
233
                boolean activeMessages = messageCount > 0;
234
                boolean currentUserIsSubmitter = regDto.getSubmitterUserName() != null && regDto.getSubmitterUserName().equals(UserHelper.fromSession().userName());
235
                boolean currentUserIsCurator = UserHelper.fromSession().userIsRegistrationCurator();
236
                messageButton.setEnabled(false);
237
                if(currentUserIsCurator){
238
                    if(currentUserIsSubmitter){
239
                        messageButton.setDescription("No point sending messages to your self.");
240
                    } else {
241
                        messageButton.setEnabled(true);
242
                        messageButton.setDescription("Open the messages dialog.");
243
                    }
244
                } else {
245
                    messageButton.setDescription("Sorry, only a curator can start a conversation.");
246
                }
247
                if(activeMessages){
248
                    messageButton.setEnabled(true);
249
                    messageButton.addStyleName(EditValoTheme.BUTTON_HIGHLITE);
250
                    String who = currentUserIsSubmitter ? "curator" : "submitter";
251
                    messageButton.setDescription("The " + who + " is looking forward to your reply.");
252

    
253
                }
254
            } catch (ExternalServiceException e) {
255
                messageButton.setComponentError(new SystemError(e.getMessage(), e));
256
            }
257
        }
258

    
259
    }
260

    
261

    
262
    /**
263
     * @param referenceID
264
     */
265
    protected void loadWorkingSet(UUID referenceUuid) {
266
        try {
267
            workingset = getWorkingSetService().loadWorkingSetByReferenceUuid(referenceUuid);
268
        } catch (RegistrationValidationException error) {
269
            logger.error(error);
270
            Window errorDialog = new Window("Validation Error");
271
            errorDialog.setModal(true);
272
            VerticalLayout subContent = new VerticalLayout();
273
            subContent.setMargin(true);
274
            errorDialog.setContent(subContent);
275
            subContent.addComponent(new Label(error.getMessage()));
276
            UI.getCurrent().addWindow(errorDialog);
277
        }
278
        if(workingset == null || workingset.getCitationUuid() == null){
279
            Reference citation = getRepo().getReferenceService().find(referenceUuid);
280
            workingset = new RegistrationWorkingSet(citation);
281
        }
282
    }
283

    
284

    
285
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
286
    public void onReferenceEditorActionAdd(ReferenceEditorAction event) {
287

    
288
        if(!checkFromOwnView(event)){
289
            return;
290
        }
291

    
292
        ReferencePopupEditor popup = getNavigationManager().showInPopup(ReferencePopupEditor.class, getView(), null);
293
        popup.withReferenceTypes(RegistrationUIDefaults.PRINTPUB_REFERENCE_TYPES);
294
        popup.loadInEditor(null);
295
    }
296

    
297
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
298
    public void onReferenceEditorActionEdit(ReferenceEditorAction event) {
299

    
300
        if(!checkFromOwnView(event)){
301
            return;
302
        }
303
        ReferencePopupEditor popup = getNavigationManager().showInPopup(ReferencePopupEditor.class, getView(), null);
304
        popup.withReferenceTypes(RegistrationUIDefaults.PRINTPUB_REFERENCE_TYPES);
305
        popup.withDeleteButton(true);
306
        popup.loadInEditor(event.getEntityUuid());
307
    }
308

    
309
    @EventBusListenerMethod
310
    public void onDoneWithReferencePopupEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
311
        if(event.getPopup() instanceof ReferencePopupEditor){
312
            if(event.getReason().equals(Reason.SAVE)){
313
                refreshView(true);
314
            }
315
        }
316
    }
317

    
318
    @EventBusListenerMethod
319
    public void onDoneWithSpecimenTypeDesignationWorkingsetPopupEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
320
        if(event.getPopup() instanceof SpecimenTypeDesignationWorkingsetPopupEditor){
321
            if(event.getReason().equals(Reason.SAVE)){
322
                refreshView(true);
323
            }
324
        }
325
    }
326

    
327
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
328
    public void onRegistrationEditorAction(RegistrationEditorAction event) {
329

    
330
        if(!checkFromOwnView(event)){
331
            return;
332
        }
333

    
334
        RegistrationPopupEditor popup = getNavigationManager().showInPopup(RegistrationPopupEditor.class, getView(), null);
335
        popup.loadInEditor(event.getEntityUuid());
336
    }
337

    
338
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
339
    public void onTaxonNameEditorActionEdit(TaxonNameEditorAction event) {
340

    
341
        if(!checkFromOwnView(event)){
342
            return;
343
        }
344

    
345
        TaxonNamePopupEditor popup = getNavigationManager().showInPopup(TaxonNamePopupEditor.class, getView(), null);
346
        popup.setParentEditorActionContext(event.getContext());
347
        popup.withDeleteButton(true);
348
        configureTaxonNameEditor(popup);
349
        popup.loadInEditor(event.getEntityUuid());
350
        if(event.hasSource() && event.getSource().isReadOnly()){
351
            // avoid resetting readonly to false
352
            popup.setReadOnly(true);
353
        }
354

    
355
    }
356

    
357

    
358
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
359
    public void onTaxonNameEditorActionAdd(TaxonNameEditorAction event) {
360

    
361
        if(!checkFromOwnView(event)){
362
            return;
363
        }
364

    
365
        newTaxonNameForRegistration = TaxonNameFactory.NewNameInstance(RegistrationUIDefaults.NOMENCLATURAL_CODE, Rank.SPECIES());
366
        newTaxonNameForRegistration.setNomenclaturalReference(getRepo().getReferenceService().find(workingset.getCitationUuid()));
367
        EntityChangeEvent nameSaveEvent = getTaxonNameStore().saveBean(newTaxonNameForRegistration, (AbstractView) getView());
368
        newTaxonNameForRegistration = getRepo().getNameService().find(nameSaveEvent.getEntityUuid());
369
        TaxonNamePopupEditor popup = getNavigationManager().showInPopup(TaxonNamePopupEditor.class, getView(), null);
370
        popup.setParentEditorActionContext(event.getContext());
371
        popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE,CRUD.DELETE));
372
        popup.withDeleteButton(true);
373
        configureTaxonNameEditor(popup);
374
        popup.loadInEditor(newTaxonNameForRegistration.getUuid());
375
    }
376

    
377
    /**
378
     * TODO consider putting this into a Configurer Bean per UIScope.
379
     * In the configurator bean this methods popup papamerter should be of the type
380
     * AbstractPopupEditor
381
     *
382
     * @param popup
383
     */
384
    protected void configureTaxonNameEditor(TaxonNamePopupEditorView popup) {
385
        popup.enableMode(TaxonNamePopupEditorMode.AUTOFILL_AUTHORSHIP_DATA);
386
        popup.enableMode(TaxonNamePopupEditorMode.NOMENCLATURALREFERENCE_SECTION_EDITING_ONLY);
387
        // popup.enableMode(TaxonNamePopupEditorMode.REQUIRE_NOMENCLATURALREFERENCE);
388
    }
389

    
390
    /**
391
     * Creates a new <code>Registration</code> for a new name that has just been edited
392
     * using the <code>TaxonNamePopupEditor</code>. The new name was previously created
393
     * in this presenter as <code>newTaxonNameForRegistration</code> (see {@link #onTaxonNameEditorActionAdd(TaxonNameEditorAction)})
394
     * and is either filled with data (<code>Reason.SAVE</code>) or it is still empty
395
     * (<code>Reason.CANCEL</code>).
396
     *
397
     *
398
     * @param event
399
     * @throws RegistrationValidationException
400
     */
401
    @EventBusListenerMethod
402
    public void onDoneWithTaxonnameEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
403
        if(event.getPopup() instanceof TaxonNamePopupEditor){
404
            TransactionStatus txStatus = getRepo().startTransaction();
405
            if(event.getReason().equals(Reason.SAVE)){
406
                if(newTaxonNameForRegistration != null){
407
                    UUID taxonNameUuid = newTaxonNameForRegistration.getUuid();
408
                    getRepo().getSession().refresh(newTaxonNameForRegistration);
409
                    Registration reg = createNewRegistrationForName(taxonNameUuid);
410
                    // reload workingset into current session
411
                    loadWorkingSet(workingset.getCitationUuid());
412
                    workingset.add(reg);
413
                }
414
                refreshView(true);
415
            } else if(event.getReason().equals(Reason.CANCEL)){
416
                if(newTaxonNameForRegistration != null){
417
                    // clean up
418
                    getTaxonNameStore().deleteBean(newTaxonNameForRegistration, (AbstractView) getView());
419
                }
420
            }
421
            getRepo().commitTransaction(txStatus);
422
            newTaxonNameForRegistration = null;
423
        }
424
    }
425

    
426

    
427
    /**
428
     * Creates a new Registration for an exiting (previously published name).
429
     *
430
     * @param event
431
     * @throws RegistrationValidationException
432
     */
433
    @EventBusListenerMethod
434
    public void onRegistrationWorkflowEventActionStart(RegistrationWorkingsetAction event) throws RegistrationValidationException {
435

    
436
        if(!event.isStart()){
437
            return;
438
        }
439

    
440
        getView().getAddExistingNameCombobox().commit();
441
        TaxonName typifiedName = getView().getAddExistingNameCombobox().getValue();
442
        if(typifiedName != null){
443
            Registration newRegistrationWithExistingName = createNewRegistrationForName(null);
444
            Reference citation = getRepo().getReferenceService().find(workingset.getCitationUuid());
445
            newRegistrationDTOWithExistingName = new RegistrationDTO(newRegistrationWithExistingName, typifiedName, citation);
446
            workingset.add(newRegistrationDTOWithExistingName);
447
            // tell the view to update the workingset
448
            getView().setWorkingset(workingset);
449
            getView().getAddExistingNameRegistrationButton().setEnabled(false);
450
            getView().getAddExistingNameRegistrationButton().setDescription("You first need to add a type designation to the previously created registration.");
451
        } else {
452
            logger.error("Seletced name is NULL");
453
        }
454

    
455
    }
456

    
457

    
458
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
459
    public void onTypeDesignationsEditorActionEdit(TypeDesignationWorkingsetEditorAction event) {
460

    
461
        if(!checkFromOwnView(event)){
462
            return;
463
        }
464

    
465
        if(event.getWorkingSetType() == TypeDesignationWorkingSetType.SPECIMEN_TYPE_DESIGNATION_WORKINGSET ){
466
            SpecimenTypeDesignationWorkingsetPopupEditor popup = getNavigationManager().showInPopup(SpecimenTypeDesignationWorkingsetPopupEditor.class, getView(), null);
467
            popup.setParentEditorActionContext(event.getContext());
468
            popup.withDeleteButton(true);
469
            popup.loadInEditor(new TypeDesignationWorkingsetEditorIdSet(event.getRegistrationUuid(), event.getBaseEntityRef()));
470
            if(event.hasSource()){
471
                // propagate readonly state from source button to popup
472
                popup.setReadOnly(event.getSource().isReadOnly());
473
            }
474
        } else {
475
            NameTypeDesignationPopupEditor popup = getNavigationManager().showInPopup(NameTypeDesignationPopupEditor.class, getView(), null);
476
            popup.setParentEditorActionContext(event.getContext());
477
            popup.withDeleteButton(true);
478
            popup.loadInEditor(new TypeDesignationWorkingsetEditorIdSet(event.getRegistrationUuid(), event.getBaseEntityRef()));
479

    
480
            popup.getCitationCombobox().setEnabled(false);
481
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
482

    
483
            if(event.hasSource()){
484
                // propagate readonly state from source button to popup
485
                popup.setReadOnly(event.getSource().isReadOnly());
486
            }
487
            newNameTypeDesignationTarget = workingset.getRegistrationDTO(event.getRegistrationUuid()).get();
488
        }
489
    }
490

    
491
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
492
    public void onTypeDesignationWorkingsetAdd(TypeDesignationWorkingsetEditorAction event) {
493

    
494
        if(!event.hasSource()){
495
            return;
496
        }
497

    
498
        if(event.getWorkingSetType() == TypeDesignationWorkingSetType.SPECIMEN_TYPE_DESIGNATION_WORKINGSET){
499
            SpecimenTypeDesignationWorkingsetPopupEditor popup = getNavigationManager().showInPopup(SpecimenTypeDesignationWorkingsetPopupEditor.class, getView(), null);
500
            popup.setParentEditorActionContext(event.getContext());
501
            TypeDesignationWorkingsetEditorIdSet identifierSet;
502
            UUID typifiedNameUuid;
503
            if(newRegistrationDTOWithExistingName != null){
504
                typifiedNameUuid = newRegistrationDTOWithExistingName.getTypifiedNameRef().getUuid();
505
            } else {
506
                RegistrationDTO registrationDTO = workingset.getRegistrationDTO(event.getRegistrationUuid()).get();
507
                EntityReference typifiedNameRef = registrationDTO.getTypifiedNameRef();
508
                if(typifiedNameRef != null){
509
                    // case for registrations without name, in which case the typifiedName is only defined via the typedesignations
510
                    typifiedNameUuid = typifiedNameRef.getUuid();
511
                } else {
512
                    // case of registrations with a name in the nomenclatural act.
513
                    typifiedNameUuid = registrationDTO.getNameRef().getUuid();
514
                }
515
            }
516
            identifierSet = new TypeDesignationWorkingsetEditorIdSet(
517
                    event.getRegistrationUuid(),
518
                    getView().getCitationUuid(),
519
                    typifiedNameUuid
520
                    );
521
            popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE, CRUD.DELETE));
522
            popup.loadInEditor(identifierSet);
523
            popup.withDeleteButton(true);
524
            if(event.hasSource()){
525
                // propagate readonly state from source component to popup
526
                popup.setReadOnly(event.getSource().isReadOnly());
527
            }
528
        } else {
529
            NameTypeDesignationPopupEditor popup = getNavigationManager().showInPopup(NameTypeDesignationPopupEditor.class, getView(), null);
530
            popup.setParentEditorActionContext(event.getContext());
531
            popup.withDeleteButton(true);
532
            popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE, CRUD.DELETE));
533
            newNameTypeDesignationTarget = workingset.getRegistrationDTO(event.getRegistrationUuid()).get();
534
            popup.setBeanInstantiator(new BeanInstantiator<NameTypeDesignation>() {
535

    
536
                @Override
537
                public NameTypeDesignation createNewBean() {
538

    
539
                    TaxonName typifiedName = getRepo().getNameService().load(event.getTypifiedNameUuid(), Arrays.asList(new String[]{"typeDesignations", "homotypicalGroup"}));
540
                    NameTypeDesignation nameTypeDesignation  = NameTypeDesignation.NewInstance();
541
                    nameTypeDesignation.setCitation(newNameTypeDesignationTarget.getCitation());
542
                    nameTypeDesignation.getTypifiedNames().add(typifiedName);
543
                    return nameTypeDesignation;
544
                }
545
            });
546
            popup.loadInEditor(null);
547
            popup.getCitationCombobox().setEnabled(false);
548
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
549
            if(event.hasSource()){
550
                // propagate readonly state from source component to popup
551
                popup.setReadOnly(event.getSource().isReadOnly());
552
            }
553
        }
554
    }
555

    
556
    /**
557
     * Performs final actions after a TypeDesignationEditor which has been
558
     * opened to add a TypeDesignation to a Registration object which was
559
     * created for an previously published name. Prior adding a typedesignation,
560
     * the according Registration object is dangling, that has no association to
561
     * any entity denoting an nomenclatural act which has a reference to a
562
     * publication. This means that the registration object is not in the
563
     * working set.
564
     *
565
     *
566
     * @param event
567
     * @throws RegistrationValidationException
568
     */
569
    @EventBusListenerMethod
570
    public void onDoneWithTypeDesignationEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
571
        if(event.getPopup() instanceof SpecimenTypeDesignationWorkingsetPopupEditor){
572
            if(event.getReason().equals(Reason.SAVE)){
573
                refreshView(true);
574
            } else if(event.getReason().equals(Reason.CANCEL)){
575
                // noting to do
576
            }
577
            newRegistrationDTOWithExistingName = null;
578
        } else if(event.getPopup() instanceof NameTypeDesignationPopupEditor){
579
            if(event.getReason().equals(Reason.SAVE)){
580
                UUID uuid = ((NameTypeDesignationPopupEditor)event.getPopup()).getBean().getUuid();
581

    
582
                Session session = getRepo().getSessionFactory().openSession();
583
                Transaction txstate = session.beginTransaction();
584
                TypeDesignationBase<?> nameTypeDesignation = getRepo().getNameService().loadTypeDesignation(uuid, Arrays.asList(""));
585
                // only load the typeDesignations with the registration so that the typified name can  not be twice in the session
586
                // otherwise multiple representation problems might occur
587
                Registration registration = getRepo().getRegistrationService().load(newNameTypeDesignationTarget.getUuid(), Arrays.asList("typeDesignations"));
588
                registration.getTypeDesignations().add(nameTypeDesignation);
589
                session.merge(registration);
590
                txstate.commit();
591
                session.close();
592

    
593
                refreshView(true);
594
            } else if(event.getReason().equals(Reason.CANCEL)){
595
                // noting to do
596
            }
597
            newNameTypeDesignationTarget = null;
598
        }
599
        // ignore other editors
600
    }
601

    
602

    
603
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationWorkingSet.class)
604
    public void onShowDetailsEventForRegistrationWorkingSet(ShowDetailsEvent<RegistrationWorkingSet,?> event) {
605

    
606
        if(event.getProperty().equals(RegistrationItem.VALIDATION_PROBLEMS)){
607
            List<String> messages = new ArrayList<>();
608
            for(RegistrationDTO dto : workingset.getRegistrationDTOs()){
609
                dto.getValidationProblems().forEach(m -> messages.add(dto.getSummary() + ": " + m));
610
            }
611
            getView().openDetailsPopup("Validation Problems", messages);
612
        }
613
    }
614

    
615
    @EventBusListenerMethod
616
    public void onEntityChangeEvent(EntityChangeEvent event){
617
        if(workingset == null){
618
            return;
619
        }
620
        if(Reference.class.isAssignableFrom(event.getEntityType())){
621
            if(workingset.getCitationUuid().equals(event.getEntityUuid())){
622
                refreshView(true);
623
            }
624
        } else
625
        if(Registration.class.isAssignableFrom(event.getEntityType())){
626
            if(workingset.getRegistrations().stream().anyMatch(reg -> reg.getUuid() == event.getEntityUuid())){
627
                refreshView(true);
628
            }
629
        } else
630
        if(TaxonName.class.isAssignableFrom(event.getEntityType())){
631
            if(event.getType().equals(EntityChangeEvent.Type.CREATED)){
632
                // new name! create a blocking registration
633
                Stack<EditorActionContext>context = ((AbstractPopupEditor)event.getSourceView()).getEditorActionContext();
634
                EditorActionContext rootContext = context.get(0);
635
                if(rootContext.getParentView().equals(getView())){
636
                    Registration blockingRegistration = createNewRegistrationForName(event.getEntityUuid());
637
                    TypedEntityReference<Registration> regReference = (TypedEntityReference<Registration>)rootContext.getParentEntity();
638
                    Registration registration = getRepo().getRegistrationService().load(regReference.getUuid(), REGISTRATION_INIT_STRATEGY);
639
                    registration.getBlockedBy().add(blockingRegistration);
640
                    getRepo().getRegistrationService().saveOrUpdate(registration);
641
                    logger.debug("Blocking registration created");
642
                } else {
643
                    logger.debug("Nn blocking registration, since a new name for a new registration has been created");
644
                }
645
            }
646
            if(workingset.getRegistrationDTOs().stream().anyMatch(reg ->
647
                reg.getTypifiedNameRef() != null
648
                && reg.getTypifiedNameRef().getUuid().equals(event.getEntityUuid()))){
649
                    refreshView(true);
650
            }
651
        } else
652
        if(TypeDesignationBase.class.isAssignableFrom(event.getEntityType())){
653
            if(workingset.getRegistrationDTOs().stream().anyMatch(
654
                    reg -> reg.getTypeDesignations() != null && reg.getTypeDesignations().stream().anyMatch(
655
                            td -> td.getUuid() == event.getEntityUuid()
656
                            )
657
                        )
658
                    ){
659
                refreshView(true);
660
            }
661
        }
662
    }
663

    
664

    
665
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationDTO.class)
666
    public void onShowDetailsEventForRegistrationDTO(ShowDetailsEvent<RegistrationDTO, UUID> event) {
667

    
668
        // FIXME check from own view!!!
669
        if(getView() == null){
670
            return;
671
        }
672

    
673
        UUID registrationUuid = event.getIdentifier();
674

    
675
        RegistrationDTO regDto = getWorkingSetService().loadDtoByUuid(registrationUuid);
676
        if(event.getProperty().equals(RegistrationItem.BLOCKED_BY)){
677

    
678
            Set<RegistrationDTO> blockingRegs = getWorkingSetService().loadBlockingRegistrations(registrationUuid);
679
            getView().setBlockingRegistrations(registrationUuid, blockingRegs);
680
        } else if(event.getProperty().equals(RegistrationItem.MESSAGES)){
681

    
682
            RegistrationMessagesPopup popup = getNavigationManager().showInPopup(RegistrationMessagesPopup.class, getView(), null);
683
            popup.loadMessagesFor(regDto.getUuid());
684

    
685
        } else if(event.getProperty().equals(RegistrationItem.VALIDATION_PROBLEMS)){
686
            getView().openDetailsPopup("Validation Problems", regDto.getValidationProblems());
687
        }
688

    
689

    
690
    }
691

    
692
}
(13-13/20)