Project

General

Profile

Download (12.6 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.ArrayList;
12
import java.util.Arrays;
13
import java.util.HashSet;
14
import java.util.Iterator;
15
import java.util.List;
16
import java.util.Set;
17

    
18
import org.hibernate.Session;
19
import org.vaadin.viritin.fields.AbstractElementCollection;
20

    
21
import eu.etaxonomy.cdm.api.service.IRegistrationService;
22
import eu.etaxonomy.cdm.model.common.VersionableEntity;
23
import eu.etaxonomy.cdm.model.location.Country;
24
import eu.etaxonomy.cdm.model.name.Registration;
25
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
26
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
27
import eu.etaxonomy.cdm.model.occurrence.Collection;
28
import eu.etaxonomy.cdm.model.occurrence.DerivationEvent;
29
import eu.etaxonomy.cdm.model.occurrence.DerivationEventType;
30
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
31
import eu.etaxonomy.cdm.model.occurrence.FieldUnit;
32
import eu.etaxonomy.cdm.model.occurrence.GatheringEvent;
33
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
34
import eu.etaxonomy.cdm.model.reference.Reference;
35
import eu.etaxonomy.cdm.service.CdmFilterablePagingProvider;
36
import eu.etaxonomy.cdm.service.CdmStore;
37
import eu.etaxonomy.cdm.vaadin.component.CdmBeanItemContainerFactory;
38
import eu.etaxonomy.cdm.vaadin.model.TypedEntityReference;
39
import eu.etaxonomy.cdm.vaadin.model.registration.DerivationEventTypes;
40
import eu.etaxonomy.cdm.vaadin.model.registration.RegistrationTermLists;
41
import eu.etaxonomy.cdm.vaadin.model.registration.SpecimenTypeDesignationWorkingSetDTO;
42
import eu.etaxonomy.cdm.vaadin.util.CdmTitleCacheCaptionGenerator;
43
import eu.etaxonomy.cdm.vaadin.util.converter.TypeDesignationSetManager.TypeDesignationWorkingSet;
44
import eu.etaxonomy.cdm.vaadin.view.registration.RegistrationDTO;
45
import eu.etaxonomy.vaadin.mvp.AbstractEditorPresenter;
46
/**
47
 * SpecimenTypeDesignationWorkingsetPopupEditorView implementation must override the showInEditor() method,
48
 * see {@link #prepareAsFieldGroupDataSource()} for details.
49
 *
50
 * @author a.kohlbecker
51
 * @since Jun 13, 2017
52
 *
53
 */
54
public class SpecimenTypeDesignationWorkingsetEditorPresenter
55
    extends AbstractEditorPresenter<SpecimenTypeDesignationWorkingSetDTO , SpecimenTypeDesignationWorkingsetPopupEditorView> {
56

    
57
    private static final long serialVersionUID = 4255636253714476918L;
58

    
59
    private List<String> specimenTypeDesignationWorkingsetInitStrategy = Arrays.asList(new String[]{
60
            "typeDesignations.typeStatus.representations",
61
            "typeDesignations.typeSpecimen.sources",
62
            "typeDesignations.typeSpecimen.mediaSpecimen.representations.parts",
63
            "typeDesignations.typeSpecimen.collection",
64
            "typeDesignations.typeSpecimen.derivedFrom.type",
65
            "typeDesignations.typeSpecimen.derivedFrom.derivatives",
66
            // Need to initialize all properties of the DerivedUnit to avoid LIEs while converting DerivedUnit with the DerivedUnitConverter:
67
            "typeDesignations.typeSpecimen.*",
68
    });
69

    
70
    CdmStore<Registration, IRegistrationService> store ;
71

    
72
    protected CdmStore<Registration, IRegistrationService> getStore() {
73
        if(store == null){
74
            store = new CdmStore<>(getRepo(), getRepo().getRegistrationService());
75
        }
76
        return store;
77
    }
78

    
79

    
80
    /**
81
     * {@inheritDoc}
82
     */
83
    @Override
84
    protected SpecimenTypeDesignationWorkingSetDTO loadBeanById(Object identifier) {
85

    
86
        SpecimenTypeDesignationWorkingSetDTO workingSet;
87
        if(identifier != null){
88
            RegistrationAndWorkingsetId registrationAndWorkingsetId = (RegistrationAndWorkingsetId)identifier;
89
            List<Integer> ids = new ArrayList<>();
90
            ids.add(registrationAndWorkingsetId.registrationId);
91
            Registration reg = getRepo().getRegistrationService().loadByIds(ids, specimenTypeDesignationWorkingsetInitStrategy).get(0);
92
            RegistrationDTO regDTO = new RegistrationDTO(reg);
93
            TypeDesignationWorkingSet typeDesignationWorkingSet = regDTO.getTypeDesignationWorkingSet(registrationAndWorkingsetId.workingsetId);
94
            workingSet = regDTO.getSpecimenTypeDesignationWorkingSetDTO(typeDesignationWorkingSet.getBaseEntityReference());
95
        } else {
96
            workingSet = null;
97
        }
98
        return workingSet;
99
    }
100

    
101

    
102
    /**
103
     * {@inheritDoc}
104
     */
105
    @SuppressWarnings("serial")
106
    @Override
107
    public void handleViewEntered() {
108

    
109
        CdmBeanItemContainerFactory selectFactory = new CdmBeanItemContainerFactory(getRepo());
110
        getView().getCountrySelectField().setContainerDataSource(selectFactory.buildBeanItemContainer(Country.uuidCountryVocabulary));
111

    
112
        getView().getTypeDesignationsCollectionField().setEditorInstantiator(new AbstractElementCollection.Instantiator<SpecimenTypeDesignationDTORow>() {
113

    
114
            CdmFilterablePagingProvider<Collection> collectionPagingProvider = new CdmFilterablePagingProvider<Collection>(getRepo().getCollectionService(), SpecimenTypeDesignationWorkingsetEditorPresenter.this);
115

    
116
            CdmFilterablePagingProvider<Reference> referencePagingProvider = new CdmFilterablePagingProvider<Reference>(getRepo().getReferenceService(), SpecimenTypeDesignationWorkingsetEditorPresenter.this);
117

    
118
            @Override
119
            public SpecimenTypeDesignationDTORow create() {
120

    
121
                SpecimenTypeDesignationDTORow row = new SpecimenTypeDesignationDTORow();
122

    
123
                row.derivationEventType.setContainerDataSource(selectFactory.buildTermItemContainer(
124
                        RegistrationTermLists.DERIVATION_EVENT_TYPE_UUIDS())
125
                        );
126
                row.derivationEventType.setNullSelectionAllowed(false);
127

    
128
                row.derivationEventType.addValueChangeListener(e -> {
129
                    SpecimenTypeDesignationDTORow currentRow = row;
130
                    updateRowItemEnablement(currentRow);
131
                });
132

    
133
                row.typeStatus.setContainerDataSource(selectFactory.buildTermItemContainer(
134
                        RegistrationTermLists.SPECIMEN_TYPE_DESIGNATION_STATUS_UUIDS())
135
                        );
136
                row.typeStatus.setNullSelectionAllowed(false);
137

    
138

    
139
                row.collection.loadFrom(
140
                        collectionPagingProvider,
141
                        collectionPagingProvider,
142
                        collectionPagingProvider.getPageSize()
143
                        );
144
                row.collection.getSelect().setCaptionGenerator(new CdmTitleCacheCaptionGenerator<Collection>());
145

    
146
                row.mediaSpecimenReference.loadFrom(
147
                        referencePagingProvider,
148
                        referencePagingProvider,
149
                        collectionPagingProvider.getPageSize()
150
                        );
151
                row.mediaSpecimenReference.getSelect().setCaptionGenerator(new CdmTitleCacheCaptionGenerator<Reference>());
152

    
153
                getView().applyDefaultComponentStyle(row.components());
154

    
155
                updateRowItemEnablement(row);
156

    
157
                return row;
158
            }
159

    
160
            private void updateRowItemEnablement(SpecimenTypeDesignationDTORow row) {
161

    
162
                DerivationEventType derivationEventType = (DerivationEventType)row.derivationEventType.getValue();
163

    
164
                boolean publishedImageType = derivationEventType != null && derivationEventType.equals(DerivationEventTypes.PUBLISHED_IMAGE());
165
                boolean unPublishedImageType = derivationEventType != null && derivationEventType.equals(DerivationEventTypes.UNPUBLISHED_IMAGE());
166

    
167
                row.mediaSpecimenReference.setEnabled(publishedImageType);
168
                row.mediaSpecimenReferenceDetail.setEnabled(publishedImageType);
169
                row.mediaUri.setEnabled(unPublishedImageType);
170

    
171
            }
172
        });
173
    }
174

    
175
    /**
176
     * {@inheritDoc}
177
     *
178
     * see also {@link SpecimenTypeDesignationWorkingsetPopupEditor#showInEditor()}
179
     */
180
    @Override
181
    protected SpecimenTypeDesignationWorkingSetDTO prepareAsFieldGroupDataSource(SpecimenTypeDesignationWorkingSetDTO bean) {
182

    
183
        if(bean.getFieldUnit() == null){
184
            // in case the base unit of the working set is not a FieldUnit all contained TypeDesignations must be modified
185
            // so that they are based on an empty FieldUnit with an associated Gathering Event
186
            if(Registration.class.isAssignableFrom(bean.getOwner().getClass())){
187
                // FIXME open Dialog to warn user about adding an empty fieldUnit to the typeDesignations
188
                logger.info("Basing all typeDesignations on a new fieldUnit");
189
                Session session = getSession();
190
                Registration reg = getRepo().getRegistrationService().find(bean.getOwner().getId());
191
                RegistrationDTO regDTO = new RegistrationDTO(reg);
192

    
193
                FieldUnit fieldUnit = FieldUnit.NewInstance();
194
                GatheringEvent gatheringEvent = GatheringEvent.NewInstance();
195
                fieldUnit.setGatheringEvent(gatheringEvent);
196
                getRepo().getOccurrenceService().save(fieldUnit);
197

    
198
                VersionableEntity baseEntity = bean.getBaseEntity();
199
                Set<TypeDesignationBase> typeDesignations = regDTO.getTypeDesignationsInWorkingSet(
200
                        new TypedEntityReference(baseEntity.getClass(), baseEntity.getId(), baseEntity.toString())
201
                        );
202
                for(TypeDesignationBase td : typeDesignations){
203
                    DerivationEvent de = DerivationEvent.NewInstance();//
204
                    de.addOriginal(fieldUnit);
205
                    de.addDerivative(((SpecimenTypeDesignation)td).getTypeSpecimen());
206
                    de.setType(DerivationEventType.GATHERING_IN_SITU());
207
                }
208

    
209
                getRepo().getRegistrationService().saveOrUpdate(reg);
210
                session.flush();
211
                session.close();
212
            } else {
213
                throw new RuntimeException("Usupported owner type " + bean.getOwner().getClass() + ", needs to be implemented.");
214
            }
215
        }
216
        return super.prepareAsFieldGroupDataSource(bean);
217
    }
218

    
219

    
220

    
221
    /**
222
     * {@inheritDoc}
223
     */
224
    @Override
225
    protected void saveBean(SpecimenTypeDesignationWorkingSetDTO dto) {
226

    
227
        Registration reg = (Registration) dto.getOwner();
228

    
229
        // associate all type designations with the fieldUnit
230
        // 1. new ones are not yet associated
231
        // 2. ones which had incomplete data are also not connected
232
        for(SpecimenTypeDesignation std : dto.getSpecimenTypeDesignations()){
233
            try {
234
                SpecimenOrObservationBase<?> original = findEarliestOriginal(std.getTypeSpecimen());
235
                if(original instanceof DerivedUnit){
236
                    DerivedUnit du = (DerivedUnit)original;
237
                    du.getDerivedFrom().addOriginal(dto.getFieldUnit());
238
                }
239
            } catch (Exception e) {
240
                // TODO Auto-generated catch block
241
                e.printStackTrace();
242
            }
243
        }
244

    
245
        // add newly added typeDesignations
246
        Set<SpecimenTypeDesignation> addCandidates = new HashSet<>();
247
        for(SpecimenTypeDesignation std : dto.getSpecimenTypeDesignations()){
248
            if(!reg.getTypeDesignations().stream().filter(td -> td.equals(std)).findFirst().isPresent()){
249
                addCandidates.add(std);
250
            }
251
        }
252
        addCandidates.forEach(std -> reg.addTypeDesignation(std));
253

    
254
        getStore().saveBean(reg);
255
    }
256

    
257
    /**
258
     * {@inheritDoc}
259
     */
260
    @Override
261
    protected void deleteBean(SpecimenTypeDesignationWorkingSetDTO bean) {
262
        // TODO Auto-generated method stub
263

    
264
    }
265

    
266

    
267
    /**
268
     * @param std
269
     * @return
270
     * @throws Exception
271
     */
272
    private SpecimenOrObservationBase<?> findEarliestOriginal(DerivedUnit du) throws Exception {
273

    
274
        SpecimenOrObservationBase original = du;
275

    
276
        while(du != null && du.getDerivedFrom() != null && !du.getDerivedFrom().getOriginals().isEmpty()) {
277
            Iterator<SpecimenOrObservationBase> it = du.getDerivedFrom().getOriginals().iterator();
278
            SpecimenOrObservationBase nextOriginal = it.next();
279
            if(nextOriginal == null){
280
                break;
281
            }
282
            original = nextOriginal;
283
            if(original instanceof DerivedUnit){
284
                du = (DerivedUnit)original;
285
            } else {
286
                // so this must be a FieldUnit,
287
               break;
288
            }
289
            if(it.hasNext()){
290
                throw new Exception(String.format("%s has more than one originals", du.toString()));
291
            }
292
        }
293
        return original;
294
    }
295

    
296

    
297
}
(3-3/8)