Project

General

Profile

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

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

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

    
56
    private static final long serialVersionUID = 4255636253714476918L;
57

    
58
    CdmStore<Registration, IRegistrationService> store;
59

    
60
    protected CdmStore<Registration, IRegistrationService> getStore() {
61
        if(store == null){
62
            store = new CdmStore<>(getRepo(), getRepo().getRegistrationService());
63
        }
64
        return store;
65
    }
66

    
67

    
68
    /**
69
     * {@inheritDoc}
70
     */
71
    @Override
72
    protected SpecimenTypeDesignationWorkingSetDTO loadBeanById(Object identifier) {
73

    
74
        SpecimenTypeDesignationWorkingSetDTO workingSet;
75
        if(identifier != null){
76
            RegistrationAndWorkingsetId registrationAndWorkingsetId = (RegistrationAndWorkingsetId)identifier;
77
            List<Integer> ids = new ArrayList<>();
78
            ids.add(registrationAndWorkingsetId.registrationId);
79
            Registration reg = getRepo().getRegistrationService().loadByIds(ids, null).get(0);
80
            RegistrationDTO regDTO = new RegistrationDTO(reg);
81
            TypeDesignationWorkingSet typeDesignationWorkingSet = regDTO.getTypeDesignationWorkingSet(registrationAndWorkingsetId.workingsetId);
82
            workingSet = regDTO.getSpecimenTypeDesignationWorkingSetDTO(typeDesignationWorkingSet.getBaseEntityReference());
83
        } else {
84
            workingSet = null;
85
        }
86
        return workingSet;
87
    }
88

    
89

    
90
    /**
91
     * {@inheritDoc}
92
     */
93
    @SuppressWarnings("serial")
94
    @Override
95
    public void handleViewEntered() {
96

    
97
        CdmBeanItemContainerFactory selectFactory = new CdmBeanItemContainerFactory(getRepo());
98
        getView().getCountrySelectField().setContainerDataSource(selectFactory.buildBeanItemContainer(Country.uuidCountryVocabulary));
99

    
100
        getView().getTypeDesignationsCollectionField().setEditorInstantiator(new AbstractElementCollection.Instantiator<SpecimenTypeDesignationDTORow>() {
101

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

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

    
106
            @Override
107
            public SpecimenTypeDesignationDTORow create() {
108

    
109
                SpecimenTypeDesignationDTORow row = new SpecimenTypeDesignationDTORow();
110

    
111
                row.derivationEventType.setContainerDataSource(selectFactory.buildTermItemContainer(
112
                        RegistrationTermLists.DERIVATION_EVENT_TYPE_UUIDS())
113
                        );
114
                row.derivationEventType.setNullSelectionAllowed(false);
115

    
116
                row.derivationEventType.addValueChangeListener(e -> {
117
                    SpecimenTypeDesignationDTORow currentRow = row;
118
                    updateRowItemEnablement(currentRow);
119
                });
120

    
121
                row.typeStatus.setContainerDataSource(selectFactory.buildTermItemContainer(
122
                        RegistrationTermLists.SPECIMEN_TYPE_DESIGNATION_STATUS_UUIDS())
123
                        );
124
                row.typeStatus.setNullSelectionAllowed(false);
125

    
126

    
127
                row.collection.loadFrom(
128
                        collectionPagingProvider,
129
                        collectionPagingProvider,
130
                        collectionPagingProvider.getPageSize()
131
                        );
132
                row.collection.getSelect().setCaptionGenerator(new CdmTitleCacheCaptionGenerator<Collection>());
133

    
134
                row.mediaSpecimenReference.loadFrom(
135
                        referencePagingProvider,
136
                        referencePagingProvider,
137
                        collectionPagingProvider.getPageSize()
138
                        );
139
                row.mediaSpecimenReference.getSelect().setCaptionGenerator(new CdmTitleCacheCaptionGenerator<Reference>());
140

    
141
                getView().applyDefaultComponentStyle(row.components());
142

    
143
                updateRowItemEnablement(row);
144

    
145
                return row;
146
            }
147

    
148
            private void updateRowItemEnablement(SpecimenTypeDesignationDTORow row) {
149

    
150
                DerivationEventType derivationEventType = (DerivationEventType)row.derivationEventType.getValue();
151

    
152
                boolean publishedImageType = derivationEventType != null && derivationEventType.equals(DerivationEventTypes.PUBLISHED_IMAGE());
153
                boolean unPublishedImageType = derivationEventType != null && derivationEventType.equals(DerivationEventTypes.UNPUBLISHED_IMAGE());
154

    
155
                row.mediaSpecimenReference.setEnabled(publishedImageType);
156
                row.mediaSpecimenReferenceDetail.setEnabled(publishedImageType);
157
                row.mediaUri.setEnabled(unPublishedImageType);
158

    
159
            }
160
        });
161
    }
162

    
163
    /**
164
     * {@inheritDoc}
165
     *
166
     * see also {@link SpecimenTypeDesignationWorkingsetPopupEditor#showInEditor()}
167
     */
168
    @Override
169
    protected SpecimenTypeDesignationWorkingSetDTO prepareAsFieldGroupDataSource(SpecimenTypeDesignationWorkingSetDTO bean) {
170

    
171
        if(bean.getFieldUnit() == null){
172
            // in case the base unit of the working set is not a FieldUnit all contained TypeDesignations must be modified
173
            // so that they are based on an empty FieldUnit with an associated Gathering Event
174
            if(Registration.class.isAssignableFrom(bean.getOwner().getClass())){
175
                // FIXME open Dialog to warn user about adding an empty fieldUnit to the typeDesignations
176
                logger.info("Basing all typeDesignations on a new fieldUnit");
177
                Session session = getSession();
178
                Registration reg = getRepo().getRegistrationService().find(bean.getOwner().getId());
179
                RegistrationDTO regDTO = new RegistrationDTO(reg);
180

    
181
                FieldUnit fieldUnit = FieldUnit.NewInstance();
182
                GatheringEvent gatheringEvent = GatheringEvent.NewInstance();
183
                fieldUnit.setGatheringEvent(gatheringEvent);
184
                getRepo().getOccurrenceService().save(fieldUnit);
185

    
186
                VersionableEntity baseEntity = bean.getBaseEntity();
187
                Set<TypeDesignationBase> typeDesignations = regDTO.getTypeDesignationsInWorkingSet(
188
                        new TypedEntityReference(baseEntity.getClass(), baseEntity.getId(), baseEntity.toString())
189
                        );
190
                for(TypeDesignationBase td : typeDesignations){
191
                    DerivationEvent de = DerivationEvent.NewInstance();//
192
                    de.addOriginal(fieldUnit);
193
                    de.addDerivative(((SpecimenTypeDesignation)td).getTypeSpecimen());
194
                    de.setType(DerivationEventType.GATHERING_IN_SITU());
195
                }
196

    
197
                getRepo().getRegistrationService().saveOrUpdate(reg);
198
                session.flush();
199
                session.close();
200
            } else {
201
                throw new RuntimeException("Usupported owner type " + bean.getOwner().getClass() + ", needs to be implemented.");
202
            }
203
        }
204
        return super.prepareAsFieldGroupDataSource(bean);
205
    }
206

    
207

    
208

    
209
    /**
210
     * {@inheritDoc}
211
     */
212
    @Override
213
    protected void saveBean(SpecimenTypeDesignationWorkingSetDTO dto) {
214

    
215
        Registration reg = (Registration) dto.getOwner();
216

    
217
        // associate all type designations with the fieldUnit
218
        // 1. new ones are not yet associated
219
        // 2. ones which had incomplete data are also not connected
220
        for(SpecimenTypeDesignation std : dto.getSpecimenTypeDesignations()){
221
            try {
222
                SpecimenOrObservationBase<?> original = findEarliestOriginal(std.getTypeSpecimen());
223
                if(original instanceof DerivedUnit){
224
                    DerivedUnit du = (DerivedUnit)original;
225
                    du.getDerivedFrom().addOriginal(dto.getFieldUnit());
226
                }
227
            } catch (Exception e) {
228
                // TODO Auto-generated catch block
229
                e.printStackTrace();
230
            }
231
        }
232

    
233
        // add newly added typeDesignations
234
        Set<SpecimenTypeDesignation> addCandidates = new HashSet<>();
235
        for(SpecimenTypeDesignation std : dto.getSpecimenTypeDesignations()){
236
            if(!reg.getTypeDesignations().stream().filter(td -> td.equals(std)).findFirst().isPresent()){
237
                addCandidates.add(std);
238
            }
239
        }
240
        addCandidates.forEach(std -> reg.addTypeDesignation(std));
241

    
242
        getStore().saveBean(reg);
243
    }
244

    
245
    /**
246
     * {@inheritDoc}
247
     */
248
    @Override
249
    protected void deleteBean(SpecimenTypeDesignationWorkingSetDTO bean) {
250
        // TODO Auto-generated method stub
251

    
252
    }
253

    
254

    
255
    /**
256
     * @param std
257
     * @return
258
     * @throws Exception
259
     */
260
    private SpecimenOrObservationBase<?> findEarliestOriginal(DerivedUnit du) throws Exception {
261

    
262
        SpecimenOrObservationBase original = du;
263

    
264
        while(du != null && du.getDerivedFrom() != null && !du.getDerivedFrom().getOriginals().isEmpty()) {
265
            Iterator<SpecimenOrObservationBase> it = du.getDerivedFrom().getOriginals().iterator();
266
            SpecimenOrObservationBase nextOriginal = it.next();
267
            if(nextOriginal == null){
268
                break;
269
            }
270
            original = nextOriginal;
271
            if(original instanceof DerivedUnit){
272
                du = (DerivedUnit)original;
273
            } else {
274
                // so this must be a FieldUnit,
275
               break;
276
            }
277
            if(it.hasNext()){
278
                throw new Exception(String.format("%s has more than one originals", du.toString()));
279
            }
280
        }
281
        return original;
282
    }
283

    
284

    
285
}
(3-3/8)