View Javadoc
1   package fr.ifremer.tutti.persistence.service;
2   
3   /*
4    * #%L
5    * Tutti :: Persistence
6    * %%
7    * Copyright (C) 2012 - 2014 Ifremer
8    * %%
9    * This program is free software: you can redistribute it and/or modify
10   * it under the terms of the GNU General Public License as
11   * published by the Free Software Foundation, either version 3 of the 
12   * License, or (at your option) any later version.
13   * 
14   * This program is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   * GNU General Public License for more details.
18   * 
19   * You should have received a copy of the GNU General Public 
20   * License along with this program.  If not, see
21   * <http://www.gnu.org/licenses/gpl-3.0.html>.
22   * #L%
23   */
24  
25  import com.google.common.base.Preconditions;
26  import com.google.common.collect.Lists;
27  import fr.ifremer.adagio.core.dao.administration.programStrategy.Program;
28  import fr.ifremer.adagio.core.dao.administration.user.DepartmentId;
29  import fr.ifremer.adagio.core.dao.administration.user.DepartmentImpl;
30  import fr.ifremer.adagio.core.dao.administration.user.PersonId;
31  import fr.ifremer.adagio.core.dao.administration.user.PersonImpl;
32  import fr.ifremer.adagio.core.dao.data.operation.FishingOperationImpl;
33  import fr.ifremer.adagio.core.dao.data.sample.Sample;
34  import fr.ifremer.adagio.core.dao.referential.QualityFlagCode;
35  import fr.ifremer.adagio.core.dao.referential.QualityFlagImpl;
36  import fr.ifremer.adagio.core.dao.referential.pmfm.Matrix;
37  import fr.ifremer.adagio.core.dao.referential.pmfm.MatrixId;
38  import fr.ifremer.adagio.core.dao.referential.pmfm.MatrixImpl;
39  import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxonImpl;
40  import fr.ifremer.tutti.persistence.entities.CaracteristicMap;
41  import fr.ifremer.tutti.persistence.entities.TuttiEntities;
42  import fr.ifremer.tutti.persistence.entities.data.AccidentalBatch;
43  import fr.ifremer.tutti.persistence.entities.data.AccidentalBatchs;
44  import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
45  import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
46  import fr.ifremer.tutti.persistence.entities.referential.Species;
47  import fr.ifremer.tutti.persistence.service.referential.CaracteristicPersistenceService;
48  import fr.ifremer.tutti.persistence.service.referential.SpeciesPersistenceService;
49  import fr.ifremer.tutti.persistence.service.util.SamplePersistenceHelper;
50  import fr.ifremer.tutti.persistence.service.util.SynchronizationStatusHelper;
51  import org.apache.commons.collections4.CollectionUtils;
52  import org.apache.commons.logging.Log;
53  import org.apache.commons.logging.LogFactory;
54  import org.hibernate.type.IntegerType;
55  import org.springframework.stereotype.Service;
56  
57  import javax.annotation.Resource;
58  import java.util.ArrayList;
59  import java.util.Collection;
60  import java.util.Collections;
61  import java.util.Iterator;
62  import java.util.List;
63  
64  /**
65   * @author Tony Chemit - chemit@codelutin.com
66   * @since 0.3
67   */
68  @Service("accidentalBatchPersistenceService")
69  public class AccidentalBatchPersistenceServiceImpl extends AbstractPersistenceService implements AccidentalBatchPersistenceService {
70  
71      /** Logger. */
72      private static final Log log =
73              LogFactory.getLog(AccidentalBatchPersistenceServiceImpl.class);
74  
75      @Resource(name = "caracteristicPersistenceService")
76      private CaracteristicPersistenceService caracteristicService;
77  
78      @Resource(name = "speciesPersistenceService")
79      private SpeciesPersistenceService speciesService;
80  
81      @Resource(name = "samplePersistenceHelper")
82      protected SamplePersistenceHelper samplePersistenceHelper;
83  
84      @Resource(name = "synchronizationStatusHelper")
85      protected SynchronizationStatusHelper synchronizationStatusHelper;
86  
87      @Override
88      public List<AccidentalBatch> getAllAccidentalBatch(Integer fishingOperationId) {
89          Preconditions.checkNotNull(fishingOperationId);
90  
91          Iterator<Object[]> list = queryList(
92                  "allFishingOperationSamplesWithoutBatch",
93                  "fishingOperationId", IntegerType.INSTANCE, fishingOperationId
94          );
95  
96          List<AccidentalBatch> result = Lists.newArrayList();
97  
98          while (list.hasNext()) {
99              Object[] source = list.next();
100 
101             AccidentalBatch accidentalBatch = AccidentalBatchs.newAccidentalBatch();
102 
103             int colIndex = 0;
104 
105             // Id
106             accidentalBatch.setId((Integer) source[colIndex++]);
107 
108             // TaxonId
109             Integer taxonId = (Integer) source[colIndex++];
110             Species species = speciesService.getSpeciesByReferenceTaxonId(taxonId);
111             accidentalBatch.setSpecies(species);
112 
113             // Comment
114             accidentalBatch.setComment((String) source[colIndex++]);
115 
116             // synchronizationStatus
117             accidentalBatch.setSynchronizationStatus((String) source[colIndex]);
118 
119             // Sample Measurements
120             accidentalBatch.setCaracteristics(new CaracteristicMap());
121 
122             // fill all measurements
123             fillSampleMeasurements(accidentalBatch);
124 
125             result.add(accidentalBatch);
126         }
127         return Collections.unmodifiableList(result);
128     }
129 
130     @Override
131     public Collection<AccidentalBatch> createAccidentalBatches(Collection<AccidentalBatch> beans) {
132 
133         Preconditions.checkNotNull(beans);
134         Collection<AccidentalBatch> result = new ArrayList<>();
135 
136         for (AccidentalBatch bean : beans) {
137             AccidentalBatch created = createAccidentalBatch(bean);
138             result.add(created);
139         }
140         return result;
141 
142     }
143 
144     @Override
145     public AccidentalBatch saveAccidentalBatch(AccidentalBatch bean) {
146         Preconditions.checkNotNull(bean);
147         Preconditions.checkState(!TuttiEntities.isNew(bean));
148         Preconditions.checkNotNull(bean.getSpecies());
149         Preconditions.checkNotNull(bean.getFishingOperation());
150         Preconditions.checkState(!TuttiEntities.isNew(bean.getFishingOperation()));
151 
152         Sample sample = samplePersistenceHelper.load(bean.getIdAsInt());
153         beanToEntity(bean, sample);
154         samplePersistenceHelper.update(sample);
155         synchronizationStatusHelper.setDirty(bean);
156         return bean;
157     }
158 
159     @Override
160     public void deleteAccidentalBatch(String id) {
161         Preconditions.checkNotNull(id);
162 
163         Integer batchId = Integer.valueOf(id);
164 
165         if (log.isInfoEnabled()) {
166             log.info("Will delete accidental batch: " + batchId);
167         }
168         samplePersistenceHelper.deleteSample(batchId);
169     }
170 
171     @Override
172     public void deleteAccidentalBatchForFishingOperation(Integer fishingOperationId) {
173         Preconditions.checkNotNull(fishingOperationId);
174 
175         List<AccidentalBatch> batches =
176                 getAllAccidentalBatch(fishingOperationId);
177 
178         if (CollectionUtils.isNotEmpty(batches)) {
179             for (AccidentalBatch batch : batches) {
180                 deleteAccidentalBatch(batch.getId());
181             }
182         }
183     }
184 
185     // ------------------------------------------------------------------------//
186     // -- Internal methods                                                   --//
187     // ------------------------------------------------------------------------//
188 
189     @Override
190     public AccidentalBatch createAccidentalBatch(AccidentalBatch bean) {
191         Preconditions.checkNotNull(bean);
192         Preconditions.checkState(TuttiEntities.isNew(bean));
193         Preconditions.checkNotNull(bean.getSpecies());
194         Preconditions.checkNotNull(bean.getFishingOperation());
195         Preconditions.checkState(!TuttiEntities.isNew(bean.getFishingOperation()));
196 
197         //TODO Optimize this (in the method we load each time the fishing operation...)
198         Sample sample = Sample.Factory.newInstance();
199         beanToEntity(bean, sample);
200         samplePersistenceHelper.create(sample);
201         bean.setId(String.valueOf(sample.getId()));
202         synchronizationStatusHelper.setDirty(bean);
203         return bean;
204     }
205 
206     protected void beanToEntity(AccidentalBatch source, Sample target) {
207 
208         if (TuttiEntities.isNew(source)) {
209 
210             // operation
211             fr.ifremer.adagio.core.dao.data.operation.FishingOperation fishingOperation;
212 
213             fishingOperation = load(FishingOperationImpl.class, source.getFishingOperation().getIdAsInt());
214             fishingOperation.getSamples().add(target); // Inverse link
215 
216             // Link to parent operation
217             target.setFishingOperation(fishingOperation);
218 
219             // Label
220             String label = fishingOperation.getId() + "_" + source.getSpecies().getReferenceTaxonId();
221             target.setLabel(label);
222 
223             // Matrix (product / batch)
224             Matrix matrix = load(MatrixImpl.class, MatrixId.PRODUCE_BATCH.getValue());
225             target.setMatrix(matrix);
226 
227             // IndividualCount
228             target.setIndividualCount((short) 1);
229 
230             // Quality Flag
231             target.setQualityFlag(load(QualityFlagImpl.class, QualityFlagCode.NOTQUALIFIED.getValue()));
232 
233             // Sample Date
234             if (target.getSampleDate() == null) {
235                 target.setSampleDate(fishingOperation.getFishingStartDateTime());
236             }
237 
238             // Create Date
239             target.setCreationDate(fishingOperation.getFishingStartDateTime());
240 
241             // Recorder Departement
242             target.setRecorderDepartment(load(DepartmentImpl.class,
243                                               DepartmentId.UNKNOWN_RECORDER_DEPARTMENT.getValue()));
244 
245             // Recorder Person
246             target.setRecorderPerson(load(PersonImpl.class,
247                                           PersonId.UNKNOWN_RECORDER_PERSON.getValue()));
248 
249             // Program
250             Program program = fishingOperation.getFishingTrip().getProgram();
251             target.setProgram(program);
252         }
253 
254         // Id
255         target.setId(source.getIdAsInt());
256 
257         // Always use a null batch (to differ with other samples)
258         target.setBatch(null);
259 
260         // Comment
261         target.setComments(source.getComment());
262 
263         // ReferenceTaxon
264         Species species = source.getSpecies();
265         Integer referenceTaxonId = species.getReferenceTaxonId();
266         target.setReferenceTaxon(load(ReferenceTaxonImpl.class, referenceTaxonId));
267 
268         // Taxongroup TODO
269 
270         // FishingAreas TODO
271 
272         // Prepare sample measurements
273 
274         CaracteristicMap caracteristics = samplePersistenceHelper.extractCommonSampleCaracteristics(source);
275 
276         if (source.getDeadOrAlive() != null) {
277             caracteristics.put(caracteristicService.getDeadOrAliveCaracteristic(), source.getDeadOrAlive());
278         }
279 
280         if (source.getGender() != null) {
281             caracteristics.put(caracteristicService.getSexCaracteristic(), source.getGender());
282         }
283 
284         samplePersistenceHelper.setSampleMeasurements(target, caracteristics);
285 
286     }
287 
288     protected void fillSampleMeasurements(AccidentalBatch batch) {
289 
290         Caracteristic deadOrAliveCaracteristic = caracteristicService.getDeadOrAliveCaracteristic();
291 
292         Caracteristic genderCaracteristic = caracteristicService.getSexCaracteristic();
293 
294         samplePersistenceHelper.loadSampleMeasurements(batch);
295 
296         CaracteristicMap caracteristics = batch.getCaracteristics();
297 
298         CaracteristicQualitativeValue deadOrAliveValue = caracteristics.removeQualitativeValue(deadOrAliveCaracteristic);
299         if (deadOrAliveValue != null) {
300             batch.setDeadOrAlive(deadOrAliveValue);
301         }
302 
303         CaracteristicQualitativeValue genderValue = caracteristics.removeQualitativeValue(genderCaracteristic);
304         if (genderValue != null) {
305             batch.setGender(genderValue);
306         }
307 
308     }
309 
310 }