Project

General

Profile

Download (27.9 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.List;
16
import java.util.Map;
17
import java.util.Optional;
18
import java.util.Set;
19
import java.util.Stack;
20
import java.util.stream.Collectors;
21

    
22
import org.apache.log4j.Logger;
23
import org.hibernate.criterion.Restrictions;
24
import org.springframework.beans.factory.annotation.Autowired;
25
import org.springframework.context.annotation.Scope;
26
import org.vaadin.spring.events.annotation.EventBusListenerMethod;
27
import org.vaadin.viritin.fields.AbstractElementCollection;
28
import org.vaadin.viritin.fields.ElementCollectionField;
29

    
30
import com.vaadin.data.util.BeanItemContainer;
31
import com.vaadin.spring.annotation.SpringComponent;
32

    
33
import eu.etaxonomy.cdm.api.service.dto.RegistrationDTO;
34
import eu.etaxonomy.cdm.cache.CdmTransientEntityAndUuidCacher;
35
import eu.etaxonomy.cdm.format.reference.ReferenceEllypsisFormatter.LabelType;
36
import eu.etaxonomy.cdm.model.ICdmEntityUuidCacher;
37
import eu.etaxonomy.cdm.model.agent.AgentBase;
38
import eu.etaxonomy.cdm.model.agent.Person;
39
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
40
import eu.etaxonomy.cdm.model.common.AnnotationType;
41
import eu.etaxonomy.cdm.model.common.CdmBase;
42
import eu.etaxonomy.cdm.model.location.Country;
43
import eu.etaxonomy.cdm.model.name.Registration;
44
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
45
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignationStatus;
46
import eu.etaxonomy.cdm.model.name.TypeDesignationStatusBase;
47
import eu.etaxonomy.cdm.model.occurrence.Collection;
48
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
49
import eu.etaxonomy.cdm.model.permission.CRUD;
50
import eu.etaxonomy.cdm.model.reference.NamedSource;
51
import eu.etaxonomy.cdm.model.reference.NamedSourceBase;
52
import eu.etaxonomy.cdm.model.reference.Reference;
53
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
54
import eu.etaxonomy.cdm.model.reference.ReferenceType;
55
import eu.etaxonomy.cdm.model.term.DefinedTermBase;
56
import eu.etaxonomy.cdm.model.term.TermType;
57
import eu.etaxonomy.cdm.persistence.dao.common.Restriction;
58
import eu.etaxonomy.cdm.persistence.dao.common.Restriction.Operator;
59
import eu.etaxonomy.cdm.persistence.query.MatchMode;
60
import eu.etaxonomy.cdm.service.CdmBeanItemContainerFactory;
61
import eu.etaxonomy.cdm.service.CdmFilterablePagingProvider;
62
import eu.etaxonomy.cdm.service.CdmFilterablePagingProviderFactory;
63
import eu.etaxonomy.cdm.service.ISpecimenTypeDesignationSetService;
64
import eu.etaxonomy.cdm.service.UserHelperAccess;
65
import eu.etaxonomy.cdm.service.initstrategies.AgentBaseInit;
66
import eu.etaxonomy.cdm.vaadin.component.CollectionRowItemCollection;
67
import eu.etaxonomy.cdm.vaadin.event.EditorActionContext;
68
import eu.etaxonomy.cdm.vaadin.event.EntityChangeEvent;
69
import eu.etaxonomy.cdm.vaadin.event.EntityChangeEventFilter;
70
import eu.etaxonomy.cdm.vaadin.event.ToOneRelatedEntityReloader;
71
import eu.etaxonomy.cdm.vaadin.model.registration.RegistrationTermLists;
72
import eu.etaxonomy.cdm.vaadin.model.registration.SpecimenTypeDesignationDTO;
73
import eu.etaxonomy.cdm.vaadin.model.registration.SpecimenTypeDesignationSetDTO;
74
import eu.etaxonomy.cdm.vaadin.ui.RegistrationUIDefaults;
75
import eu.etaxonomy.cdm.vaadin.util.CollectionCaptionGenerator;
76
import eu.etaxonomy.cdm.vaadin.util.ReferenceEllypsisCaptionGenerator;
77
import eu.etaxonomy.cdm.vaadin.util.fields.ElementCollectionHelper;
78
import eu.etaxonomy.cdm.vaadin.view.occurrence.CollectionPopupEditor;
79
import eu.etaxonomy.cdm.vaadin.view.reference.ReferencePopupEditor;
80
import eu.etaxonomy.cdm.vaadin.view.reference.RegistrationUiReferenceEditorFormConfigurator;
81
import eu.etaxonomy.vaadin.component.ToOneRelatedEntityCombobox;
82
import eu.etaxonomy.vaadin.mvp.AbstractEditorPresenter;
83
import eu.etaxonomy.vaadin.mvp.AbstractPopupEditor;
84
import eu.etaxonomy.vaadin.mvp.AbstractView;
85
import eu.etaxonomy.vaadin.mvp.BeanInstantiator;
86
/**
87
 * SpecimenTypeDesignationSetPopupEditorView implementation must override the showInEditor() method,
88
 * see {@link #prepareAsFieldGroupDataSource()} for details.
89
 *
90
 * @author a.kohlbecker
91
 * @since Jun 13, 2017
92
 */
93
@SpringComponent
94
@Scope("prototype")
95
public class SpecimenTypeDesignationSetEditorPresenter
96
    extends AbstractEditorPresenter<SpecimenTypeDesignationSetDTO,SpecimenTypeDesignationSetPopupEditorView>
97
    implements CachingPresenter, NomenclaturalActContext {
98

    
99
    private static final long serialVersionUID = 4255636253714476918L;
100

    
101
    public static final Logger logger = Logger.getLogger(SpecimenTypeDesignationSetEditorPresenter.class);
102

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

    
105
    /**
106
     * This object for this field will either be injected by the {@link PopupEditorFactory} or by a Spring
107
     * {@link BeanFactory}
108
     */
109
    @Autowired
110
    private ISpecimenTypeDesignationSetService specimenTypeDesignationSetService;
111

    
112
    @Autowired
113
    private CdmFilterablePagingProviderFactory pagingProviderFactory;
114

    
115
    @Autowired
116
    private CdmBeanItemContainerFactory cdmBeanItemContainerFactory;
117

    
118
    /**
119
     * if not null, this CRUD set is to be used to create a CdmAuthoritiy for the base entitiy which will be
120
     * granted to the current use as long this grant is not assigned yet.
121
     */
122
    private EnumSet<CRUD> crud = null;
123

    
124
    private ICdmEntityUuidCacher cache;
125

    
126
    private SpecimenTypeDesignationSetDTO<Registration> workingSetDto;
127

    
128
    private CdmFilterablePagingProvider<Reference, Reference> designationReferencePagingProvider;
129

    
130
    private CdmFilterablePagingProvider<Reference, Reference> mediaReferencePagingProvider;
131

    
132
    /**
133
     * The unit of publication in which the type designation has been published.
134
     * This may be any type listed in {@link RegistrationUIDefaults#NOMECLATURAL_PUBLICATION_UNIT_TYPES}
135
     * but never a {@link ReferenceType#Section}
136
     */
137
    private NamedSourceBase publishedUnit;
138

    
139
    private Map<CollectionPopupEditor, SpecimenTypeDesignationDTORow> collectionPopupEditorsRowMap = new HashMap<>();
140

    
141
    private Map<ReferencePopupEditor, ToOneRelatedEntityCombobox<Reference>> referencePopupEditorsCombobox = new HashMap<>();
142

    
143
    private ElementCollectionHelper<ElementCollectionField<?>> typeDesignationsCollectionFieldHelper;
144

    
145
    private Set<CollectionRowItemCollection> typeDesignationEditorRows = new HashSet<>();
146

    
147
    private java.util.Collection<CdmBase> rootEntities = new HashSet<>();
148

    
149
    private BeanInstantiator<Reference> newReferenceInstantiator;
150

    
151
    private Optional<Boolean> isInTypedesignationOnlyAct = Optional.empty();
152

    
153
    /**
154
     * Loads an existing working set from the database. This process actually involves
155
     * loading the Registration specified by the <code>RegistrationAndWorkingsetId.registrationId</code> and in
156
     * a second step to find the workingset by the <code>registrationAndWorkingsetId.workingsetId</code>.
157
     * <p>
158
     * The <code>identifier</code> must be of the type {@link TypeDesignationSetIds} whereas the
159
     * field <code>registrationId</code> must be present.
160
     * The field <code>workingsetId</code> however can be null.
161
     * I this case a new workingset with a new {@link FieldUnit} as
162
     * base entity is being created.
163
     *
164
     * @param identifier a {@link TypeDesignationSetIds}
165
     */
166
    @Override
167
    protected SpecimenTypeDesignationSetDTO<Registration> loadBeanById(Object identifier) {
168

    
169
        cache = new CdmTransientEntityAndUuidCacher(this);
170
        if(identifier != null){
171

    
172
            SpecimenTypeDesignationSetIds idset = (SpecimenTypeDesignationSetIds)identifier;
173

    
174
            if(idset.baseEntity != null){
175
                // load existing workingset
176
                workingSetDto = specimenTypeDesignationSetService.load(idset.registrationUuid, idset.baseEntity);
177
                if(workingSetDto.getFieldUnit() == null){
178
                    workingSetDto = specimenTypeDesignationSetService.fixMissingFieldUnit(workingSetDto);
179
                        // FIXME open Dialog to warn user about adding an empty fieldUnit to the typeDesignations
180
                        //       This method must go again into the presenter !!!!
181
                        logger.info("Basing all typeDesignations on a new fieldUnit");
182
                }
183
            } else {
184
                // create a new workingset, for a new fieldunit which is the base for the workingset
185
                workingSetDto = specimenTypeDesignationSetService.create(idset.getRegistrationUUID(), idset.getTypifiedNameUuid());
186
                cache.load(workingSetDto.getTypifiedName());
187
                rootEntities.add(workingSetDto.getTypifiedName());
188
            }
189
            Registration registration = workingSetDto.getOwner();
190
            // need to use load() but put() see #7214
191
            cache.load(registration);
192
            rootEntities.add(registration);
193
            setInTypedesignationOnlyAct(Optional.of(Boolean.valueOf(registration.getName() == null)));
194
            try {
195
                NamedSourceBase pubUnitSource = RegistrationDTO.findPublishedUnit(registration);
196
                if(pubUnitSource == null) {
197
                    Reference reference = getRepo().getReferenceService().load(idset.getPublishedUnitUuid());
198
                    pubUnitSource = NamedSource.NewPrimarySourceInstance(reference, null);
199
                }
200
                setPublishedUnit(pubUnitSource);
201
            } catch (Exception e) {
202
                // FIXME report error state instead
203
                logger.error("Error on finding published unit in " + registration.toString(), e);
204
            }
205
        } else {
206
            workingSetDto = null;
207
        }
208

    
209
        if (getPublishedUnit() != null) {
210
            // reduce available references to those which are sections of
211
            // the publicationUnit and the publishedUnit itself
212
            designationReferencePagingProvider.getCriteria()
213
                    .add(Restrictions.or(
214
                            Restrictions.and(
215
                                    Restrictions.eq("inReference", publishedUnit.getCitation()),
216
                                    Restrictions.eq("type", ReferenceType.Section)),
217
                            Restrictions.idEq(publishedUnit.getCitation().getId()))
218
                         );
219
            // new Reference only a sub sections of the publishedUnit
220
            newReferenceInstantiator = new BeanInstantiator<Reference>() {
221
                @Override
222
                public Reference createNewBean() {
223
                    Reference newRef = ReferenceFactory.newSection();
224
                    newRef.setInReference(publishedUnit.getCitation());
225
                    return newRef;
226
                }
227
            };
228
        }
229

    
230
        // new Reference only a sub sections of the publishedUnit
231
        newReferenceInstantiator = new BeanInstantiator<Reference>() {
232
            @Override
233
            public Reference createNewBean() {
234
                Reference newRef = ReferenceFactory.newSection();
235
                newRef.setInReference(publishedUnit.getCitation());
236
                return newRef;
237
            }
238
        };
239

    
240
        return workingSetDto;
241
    }
242

    
243

    
244
    /**
245
     * {@inheritDoc}
246
     */
247
    @SuppressWarnings("serial")
248
    @Override
249
    public void handleViewEntered() {
250

    
251
        getView().getCountrySelectField().setContainerDataSource(cdmBeanItemContainerFactory.buildVocabularyTermsItemContainer(Country.uuidCountryVocabulary));
252

    
253
        CdmFilterablePagingProvider<AgentBase, TeamOrPersonBase> termOrPersonPagingProvider = pagingProviderFactory.teamOrPersonPagingProvider();
254
        CdmFilterablePagingProvider<AgentBase, Person> personPagingProvider = pagingProviderFactory.personPagingProvider();
255
        termOrPersonPagingProvider.setInitStrategy(AgentBaseInit.TEAM_OR_PERSON_INIT_STRATEGY);
256
        // the ToOneRelatedEntityReloader is added internally in the TeamOrPersonField:
257
        getView().getCollectorField().setFilterablePersonPagingProvider(personPagingProvider, this);
258
        getView().getCollectorField().setFilterableTeamPagingProvider(termOrPersonPagingProvider, this);
259

    
260
        getView().getExactLocationField().getReferenceSystemSelect().setContainerDataSource(cdmBeanItemContainerFactory.buildTermItemContainer(TermType.ReferenceSystem));
261
        getView().getExactLocationField().getReferenceSystemSelect().setItemCaptionPropertyId("label");
262

    
263
        getView().getTypeDesignationsCollectionField().addElementRemovedListener(e -> deleteTypeDesignation(e.getElement()));
264
        getView().getTypeDesignationsCollectionField().addElementAddedListener(e -> addTypeDesignation(e.getElement()));
265

    
266
        getView().getAnnotationsField().setAnnotationTypeItemContainer(cdmBeanItemContainerFactory.buildVocabularyTermsItemContainer(
267
                AnnotationType.EDITORIAL().getVocabulary().getUuid()));
268

    
269
        typeDesignationEditorRows.clear();
270
        CdmFilterablePagingProvider<Collection, Collection> collectionPagingProvider = new CdmFilterablePagingProvider<Collection, Collection>(getRepo().getCollectionService());
271
        collectionPagingProvider.getRestrictions().add(new Restriction<>("institute.titleCache", Operator.OR, MatchMode.ANYWHERE, CdmFilterablePagingProvider.QUERY_STRING_PLACEHOLDER));
272

    
273
        designationReferencePagingProvider = pagingProviderFactory.referencePagingProvider();
274
        mediaReferencePagingProvider = pagingProviderFactory.referencePagingProvider();
275

    
276
        typeDesignationsCollectionFieldHelper = new ElementCollectionHelper(getView().getTypeDesignationsCollectionField());
277
        getView().getTypeDesignationsCollectionField().setEditorInstantiator(new AbstractElementCollection.Instantiator<SpecimenTypeDesignationDTORow>() {
278

    
279
            @Override
280
            public SpecimenTypeDesignationDTORow create() {
281

    
282
                SpecimenTypeDesignationDTORow row = new SpecimenTypeDesignationDTORow();
283

    
284
                row.kindOfUnit.setContainerDataSource(cdmBeanItemContainerFactory.buildTermItemContainer(
285
                        RegistrationTermLists.KIND_OF_UNIT_TERM_UUIDS())
286
                        );
287
                row.kindOfUnit.setNullSelectionAllowed(false);
288

    
289
                row.typeStatus.setContainerDataSource(provideTypeStatusTermItemContainer());
290
                row.typeStatus.setNullSelectionAllowed(false);
291

    
292

    
293
                row.collection.loadFrom(
294
                        collectionPagingProvider,
295
                        collectionPagingProvider,
296
                        collectionPagingProvider.getPageSize()
297
                        );
298
                row.collection.getSelect().setCaptionGenerator(new CollectionCaptionGenerator());
299
                row.collection.getSelect().addValueChangeListener(new ToOneRelatedEntityReloader<Collection>(row.collection.getSelect(),
300
                        SpecimenTypeDesignationSetEditorPresenter.this));
301
                row.collection.addClickListenerAddEntity(e -> doCollectionEditorAdd(row));
302
                row.collection.addClickListenerEditEntity(e -> {
303
                        if(row.collection.getValue() != null){
304
                            doCollectionEditorEdit(row);
305
                        }
306
                    });
307

    
308
                row.designationReference.loadFrom(
309
                        designationReferencePagingProvider,
310
                        designationReferencePagingProvider,
311
                        designationReferencePagingProvider.getPageSize()
312
                        );
313
                row.designationReference.getSelect().setCaptionGenerator(new ReferenceEllypsisCaptionGenerator(LabelType.BIBLIOGRAPHIC, row.designationReference.getSelect()));
314
                row.designationReference.getSelect().addValueChangeListener(new ToOneRelatedEntityReloader<Reference>(row.designationReference.getSelect(),
315
                        SpecimenTypeDesignationSetEditorPresenter.this));
316
                row.designationReference.addClickListenerAddEntity(e -> doReferenceEditorAdd(row.designationReference));
317
                row.designationReference.addClickListenerEditEntity(e -> {
318
                    if(row.designationReference.getValue() != null){
319
                        doReferenceEditorEdit(row.designationReference);
320
                    }
321
                });
322
                row.designationReference.setRequired(checkInTypeDesignationOnlyAct());
323
                row.designationReference.getSelect().setNullSelectionAllowed(!checkInTypeDesignationOnlyAct());
324

    
325
                row.mediaSpecimenReference.loadFrom(
326
                        mediaReferencePagingProvider,
327
                        mediaReferencePagingProvider,
328
                        mediaReferencePagingProvider.getPageSize()
329
                        );
330
                row.mediaSpecimenReference.getSelect().setCaptionGenerator(new ReferenceEllypsisCaptionGenerator(LabelType.BIBLIOGRAPHIC, row.mediaSpecimenReference.getSelect()));
331
                row.mediaSpecimenReference.getSelect().addValueChangeListener(new ToOneRelatedEntityReloader<Reference>(row.mediaSpecimenReference.getSelect(),
332
                        SpecimenTypeDesignationSetEditorPresenter.this));
333
                row.mediaSpecimenReference.addClickListenerAddEntity(e -> doReferenceEditorAdd(row.mediaSpecimenReference));
334
                row.mediaSpecimenReference.addClickListenerEditEntity(e -> {
335
                    if(row.mediaSpecimenReference.getValue() != null){
336
                        doReferenceEditorEdit(row.mediaSpecimenReference);
337
                    }
338
                });
339

    
340
                getView().applyDefaultComponentStyle(row.components());
341

    
342
                typeDesignationEditorRows.add(row);
343

    
344
                return row;
345
            }
346
        });
347
    }
348

    
349
    protected BeanItemContainer<DefinedTermBase> provideTypeStatusTermItemContainer() {
350
        BeanItemContainer<DefinedTermBase> container = cdmBeanItemContainerFactory.buildTermItemContainer(
351
                RegistrationTermLists.SPECIMEN_TYPE_DESIGNATION_STATUS_UUIDS());
352
        List<TypeDesignationStatusBase> filteredItems = container.getItemIds().stream()
353
                .filter(t -> t instanceof SpecimenTypeDesignationStatus)
354
                .map(t -> (SpecimenTypeDesignationStatus)t)
355
                .filter(tsb ->
356
                    !checkInTypeDesignationOnlyAct()
357
                    || tsb.hasDesignationSource() == true
358
                )
359
                .collect(Collectors.toList());
360
        container.removeAllItems();
361
        container.addAll(filteredItems);
362
        return container;
363
    }
364

    
365
    /**
366
     * {@inheritDoc}
367
     */
368
    @Override
369
    protected void saveBean(SpecimenTypeDesignationSetDTO dto) {
370

    
371
        if(crud != null){
372
            UserHelperAccess.userHelper().createAuthorityForCurrentUser(dto.getFieldUnit(), crud, null);
373
        }
374

    
375
        List<SpecimenTypeDesignationDTO> stdDTOs = dto.getSpecimenTypeDesignationDTOs();
376
        for(SpecimenTypeDesignationDTO stddto : stdDTOs) {
377
            // clean up
378
            if(!stddto.getTypeStatus().hasDesignationSource()) {
379
                stddto.setDesignationReference(null);
380
                stddto.setDesignationReferenceDetail(null);
381
            }
382
        }
383

    
384
        specimenTypeDesignationSetService.save(dto);
385
    }
386

    
387
    /**
388
     * {@inheritDoc}
389
     */
390
    @Override
391
    protected void deleteBean(SpecimenTypeDesignationSetDTO bean) {
392
        specimenTypeDesignationSetService.delete(bean, true);
393
    }
394

    
395
    /**
396
     * @param element
397
     * @return
398
     */
399
    private void addTypeDesignation(SpecimenTypeDesignationDTO element) {
400
        getView().updateAllowDeleteTypeDesignation();
401
    }
402

    
403

    
404
    /**
405
     * In this method the SpecimenTypeDesignation is dissociated from the Registration.
406
     * The actual deletion of the SpecimenTypeDesignation and DerivedUnit will take place in {@link #saveBean(SpecimenTypeDesignationSetDTO)}
407
     *
408
     * TODO once https://dev.e-taxonomy.eu/redmine/issues/7077 is fixed dissociating from the Registration could be removed here
409
     *
410
     * @param e
411
     * @return
412
     */
413
    private void deleteTypeDesignation(SpecimenTypeDesignationDTO element) {
414

    
415
        Registration reg = workingSetDto.getOwner();
416
        SpecimenTypeDesignation std = element.asSpecimenTypeDesignation();
417

    
418
        reg.getTypeDesignations().remove(std);
419

    
420
        getView().updateAllowDeleteTypeDesignation();
421
    }
422

    
423
    /**
424
     * @param crud
425
     */
426
    public void setGrantsForCurrentUser(EnumSet<CRUD> crud) {
427
        this.crud = crud;
428
    }
429

    
430
    /**
431
     * {@inheritDoc}
432
     */
433
    @Override
434
    public ICdmEntityUuidCacher getCache() {
435
        return cache;
436
    }
437

    
438
    @Override
439
    public void disposeCache() {
440
        cache.dispose();
441
    }
442

    
443
    public void doCollectionEditorAdd(SpecimenTypeDesignationDTORow row) {
444

    
445
        CollectionPopupEditor collectionPopupEditor = openPopupEditor(CollectionPopupEditor.class, null);
446

    
447
        collectionPopupEditor.grantToCurrentUser(COLLECTION_EDITOR_CRUD);
448
        collectionPopupEditor.withDeleteButton(true);
449
        collectionPopupEditor.loadInEditor(null);
450

    
451
        collectionPopupEditorsRowMap.put(collectionPopupEditor, row);
452
    }
453

    
454
    public void doCollectionEditorEdit(SpecimenTypeDesignationDTORow row) {
455

    
456
        CollectionPopupEditor collectionPopupEditor = openPopupEditor(CollectionPopupEditor.class, null);
457

    
458
        collectionPopupEditor.grantToCurrentUser(COLLECTION_EDITOR_CRUD);
459
        collectionPopupEditor.withDeleteButton(true);
460
        collectionPopupEditor.loadInEditor(row.collection.getValue().getUuid());
461

    
462
        collectionPopupEditorsRowMap.put(collectionPopupEditor, row);
463
    }
464

    
465

    
466
    @EventBusListenerMethod(filter = EntityChangeEventFilter.OccurrenceCollectionFilter.class)
467
    public void onCollectionEvent(EntityChangeEvent event){
468

    
469
        if(event.getSourceView() instanceof AbstractPopupEditor) {
470

    
471
            Stack<EditorActionContext> context = ((AbstractPopupEditor) event.getSourceView()).getEditorActionContext();
472
            if(context.size() > 1){
473
               AbstractView<?> parentView = context.get(context.size() - 2).getParentView();
474
               if(getView().equals(parentView)){
475
                   Collection newCollection = getRepo().getCollectionService().load(
476
                           event.getEntityUuid(), Arrays.asList(new String[]{"$.institute"})
477
                           );
478
                   cache.load(newCollection);
479

    
480
                   if(event.isCreatedType()){
481
                       //TODO use typeDesignationsCollectionFieldHelper instead to get component
482
                       SpecimenTypeDesignationDTORow row = collectionPopupEditorsRowMap.get(event.getSourceView());
483
                       ToOneRelatedEntityCombobox<Collection> combobox = row.getComponent(ToOneRelatedEntityCombobox.class, SpecimenTypeDesignationDTORow.FIELD_INDEX_COLLECTION);
484
                       combobox.setValue((Collection) event.getEntity());
485
                   } else {
486
                       //TODO use typeDesignationsCollectionFieldHelper instead to get component
487
                       for( CollectionRowItemCollection row : typeDesignationEditorRows) {
488
                           ToOneRelatedEntityCombobox<Collection> combobox = row.getComponent(ToOneRelatedEntityCombobox.class,  SpecimenTypeDesignationDTORow.FIELD_INDEX_COLLECTION);
489
                           combobox.reload();
490
                       }
491
                   }
492
               }
493
            }
494
        }
495
    }
496

    
497
    public void doReferenceEditorAdd(ToOneRelatedEntityCombobox<Reference> referenceComobox) {
498

    
499
        ReferencePopupEditor referencePopupEditor = openPopupEditor(ReferencePopupEditor.class, null);
500

    
501
        String property = typeDesignationsCollectionFieldHelper.properyFor(referenceComobox);
502
        if(property.equals(SpecimenTypeDesignationDTORow.FIELD_NAME_DESIGNATION_REFERENCE)){
503
            referencePopupEditor.withReferenceTypes(EnumSet.of(ReferenceType.Section));
504
            referencePopupEditor.grantToCurrentUser(COLLECTION_EDITOR_CRUD);
505
            referencePopupEditor.withDeleteButton(true);
506
            RegistrationUiReferenceEditorFormConfigurator
507
                .create(true).configure(referencePopupEditor, newReferenceInstantiator);
508
            referencePopupEditor.loadInEditor(null);
509
        } else {
510
            // only other option by now
511
            referencePopupEditor.withReferenceTypes(RegistrationUIDefaults.MEDIA_REFERENCE_TYPES);
512
            referencePopupEditor.grantToCurrentUser(COLLECTION_EDITOR_CRUD);
513
            referencePopupEditor.withDeleteButton(true);
514
            referencePopupEditor.loadInEditor(null);
515
        }
516

    
517
        referencePopupEditorsCombobox.put(referencePopupEditor, referenceComobox);
518
    }
519

    
520
    public void doReferenceEditorEdit(ToOneRelatedEntityCombobox<Reference> referenceComobox) {
521

    
522
        ReferencePopupEditor referencePopupEditor = openPopupEditor(ReferencePopupEditor.class, null);
523

    
524
        String property = typeDesignationsCollectionFieldHelper.properyFor(referenceComobox);
525

    
526
        if(property.equals(SpecimenTypeDesignationDTORow.FIELD_NAME_DESIGNATION_REFERENCE)){
527
            referencePopupEditor.grantToCurrentUser(COLLECTION_EDITOR_CRUD);
528
            referencePopupEditor.withDeleteButton(true);
529
            RegistrationUiReferenceEditorFormConfigurator
530
                .create(false).typeSelectReadonly(true).configure(referencePopupEditor, newReferenceInstantiator);
531
            referencePopupEditor.loadInEditor(referenceComobox.getValue().getUuid());
532
        } else {
533
            // only other option by now
534
            referencePopupEditor.withReferenceTypes(RegistrationUIDefaults.MEDIA_REFERENCE_TYPES);
535
            referencePopupEditor.grantToCurrentUser(COLLECTION_EDITOR_CRUD);
536
            referencePopupEditor.withDeleteButton(true);
537
            referencePopupEditor.loadInEditor(referenceComobox.getValue().getUuid());
538
        }
539

    
540
        referencePopupEditorsCombobox.put(referencePopupEditor, referenceComobox);
541
    }
542

    
543

    
544

    
545
    @EventBusListenerMethod(filter = EntityChangeEventFilter.ReferenceFilter.class)
546
    public void onReferenceEvent(EntityChangeEvent event){
547

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

    
551
        ToOneRelatedEntityCombobox<Reference> combobox = referencePopupEditorsCombobox.get(event.getSourceView());
552
        if(event.isCreatedType()){
553
            combobox.setValue((Reference) event.getEntity());
554
        } else {
555
            for( CollectionRowItemCollection row : typeDesignationEditorRows) {
556
                combobox.reload();
557
            }
558
        }
559
    }
560

    
561
    /**
562
     * {@inheritDoc}
563
     */
564
    @Override
565
    public void addRootEntity(CdmBase entity) {
566
        rootEntities.add(entity);
567
    }
568

    
569
    /**
570
     * {@inheritDoc}
571
     */
572
    @Override
573
    public java.util.Collection<CdmBase> getRootEntities() {
574
        return rootEntities ;
575
    }
576

    
577
    @Override
578
    public void destroy() throws Exception {
579
        super.destroy();
580
        cache.dispose();
581
    }
582

    
583
    /**
584
     * @return
585
     *  the {@link #publishedUnit}
586
     */
587
    public NamedSourceBase getPublishedUnit() {
588
        return publishedUnit;
589
    }
590

    
591
    /**
592
     * @param publishedUnit
593
     *  The unit of publication in which the type designation has been published.
594
     *  This may be any type listed in {@link RegistrationUIDefaults#NOMECLATURAL_PUBLICATION_UNIT_TYPES}
595
     */
596
    protected void setPublishedUnit(NamedSourceBase publishedUnit) throws Exception {
597
        if(publishedUnit == null) {
598
            throw new NullPointerException();
599
        }
600
        if(publishedUnit.getCitation() == null) {
601
            throw new NullPointerException("The citation of the published unit must not be null.");
602
        }
603
        if(!RegistrationUIDefaults.NOMECLATURAL_PUBLICATION_UNIT_TYPES.contains(publishedUnit.getCitation().getType())) {
604
            throw new Exception("The referrence type '"  + publishedUnit.getType() + "'is not allowed for publishedUnit.");
605
        }
606
        this.publishedUnit = publishedUnit;
607
    }
608

    
609
    @Override
610
    public void setInTypedesignationOnlyAct(Optional<Boolean> isInTypedesignationOnlyAct) {
611
        this.isInTypedesignationOnlyAct = isInTypedesignationOnlyAct;
612
    }
613

    
614
    @Override
615
    public Optional<Boolean> isInTypedesignationOnlyAct() {
616
        return isInTypedesignationOnlyAct;
617
    }
618

    
619
}
(10-10/18)