View Javadoc
1   package fr.ifremer.tutti.persistence.service.util.tree;
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.Joiner;
26  import com.google.common.collect.Sets;
27  import fr.ifremer.adagio.core.dao.data.batch.Batch;
28  import fr.ifremer.adagio.core.dao.data.batch.Batchs;
29  import fr.ifremer.adagio.core.dao.data.batch.CatchBatch;
30  import fr.ifremer.adagio.core.dao.data.batch.CatchBatchExtendDao;
31  import fr.ifremer.adagio.core.dao.data.batch.SortingBatch;
32  import fr.ifremer.adagio.core.dao.data.measure.QuantificationMeasurement;
33  import fr.ifremer.adagio.core.dao.data.measure.SortingMeasurement;
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.PmfmId;
37  import fr.ifremer.adagio.core.dao.referential.pmfm.QualitativeValueId;
38  import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxon;
39  import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxonImpl;
40  import fr.ifremer.tutti.persistence.service.AbstractPersistenceService;
41  import fr.ifremer.tutti.persistence.service.util.MeasurementPersistenceHelper;
42  import org.apache.commons.lang3.StringUtils;
43  import org.apache.commons.lang3.SystemUtils;
44  import org.apache.commons.lang3.builder.ToStringBuilder;
45  import org.apache.commons.lang3.builder.ToStringStyle;
46  import org.apache.commons.logging.Log;
47  import org.apache.commons.logging.LogFactory;
48  
49  import javax.annotation.Resource;
50  import java.util.ArrayList;
51  import java.util.Collection;
52  import java.util.Collections;
53  import java.util.Comparator;
54  import java.util.List;
55  import java.util.Set;
56  
57  /**
58   * Helper to build or navigauet into the batch tree.
59   *
60   * Created on 4/20/14.
61   *
62   * @author Tony Chemit - chemit@codelutin.com
63   * @since 3.5
64   */
65  public abstract class BatchTreeHelperSupport extends AbstractPersistenceService {
66  
67      public static final Integer SORTING_TYPE_ID = PmfmId.SCIENTIFIC_CRUISE_SORTING_TYPE.getValue();
68  
69      public static final Integer SORTING_TYPE2_ID = PmfmId.SCIENTIFIC_CRUISE_SORTING_TYPE2.getValue();
70  
71      /** Logger. */
72      private static final Log log = LogFactory.getLog(BatchTreeHelperSupport.class);
73  
74      @Resource(name = "measurementPersistenceHelper")
75      protected MeasurementPersistenceHelper measurementPersistenceHelper;
76  
77      @Resource(name = "catchBatchDao")
78      protected CatchBatchExtendDao catchBatchDao;
79  
80      protected Comparator<Batch> batchComparator = Batchs.newRankOrderComparator();
81  
82      //------------------------------------------------------------------------//
83      //-- Get CatchBatch navigation methods                                  --//
84      //------------------------------------------------------------------------//
85  
86      public final SortingBatch getVracBatch(CatchBatch batch) {
87          return getSortingBatch(batch,
88                                 "Vrac",
89                                 PmfmId.SORTED_UNSORTED.getValue(),
90                                 QualitativeValueId.SORTED_VRAC.getValue());
91      }
92  
93      public final SortingBatch getHorsVracBatch(CatchBatch batch) {
94          return getSortingBatch(batch,
95                                 "Hors Vrac",
96                                 PmfmId.SORTED_UNSORTED.getValue(),
97                                 QualitativeValueId.SORTED_HORS_VRAC.getValue());
98      }
99  
100     public final SortingBatch getOrCreateVracBatch(CatchBatch batch, Float weight, Float weightBeforeSampling) {
101         return getOrCreate(batch,
102                            batch,
103                            "Vrac",
104                            PmfmId.SORTED_UNSORTED.getValue(),
105                            QualitativeValueId.SORTED_VRAC.getValue(),
106                            weight,
107                            weightBeforeSampling,
108                            (short) 1);
109     }
110 
111     public final SortingBatch getOrCreateHorsVracBatch(CatchBatch batch) {
112         return getOrCreate(batch,
113                            batch,
114                            "Hors Vrac",
115                            PmfmId.SORTED_UNSORTED.getValue(),
116                            QualitativeValueId.SORTED_HORS_VRAC.getValue(),
117                            (short) 2);
118     }
119 
120     public final void setWeightAndSampleRatio(SortingBatch target, Float weight, Float weightBeforeSampling) {
121 
122         catchBatchDao.setSortingBatchWeights(target,
123                                              weight,
124                                              weightBeforeSampling,
125                                              PmfmId.WEIGHT_MEASURED.getValue(),
126                                              measurementPersistenceHelper.getRecorderDepartmentId());
127 
128     }
129 
130     public final void setSortingSamplingRatio(SortingBatch target, Float weight, Float weightBeforeSampling) {
131 
132         catchBatchDao.setSortingSamplingRatio(target, weight, weightBeforeSampling);
133 
134     }
135 
136     //------------------------------------------------------------------------//
137     //-- Internal methods                                                   --//
138     //------------------------------------------------------------------------//
139 
140     protected final SortingBatch get(Batch parentBatch, Integer sortingPmfmId, Integer sortingQualitativeValueId) {
141         return getSortingBatch(
142                 parentBatch,
143                 null,
144                 sortingPmfmId,
145                 sortingQualitativeValueId);
146     }
147 
148     protected final SortingBatch getSortingBatch(Batch source, String debugMessage, Integer... ids) {
149 
150         return getSortingBatch(source.getChildBatchs(), debugMessage, ids);
151     }
152 
153     protected final SortingBatch getSortingBatch(Collection<Batch> childs, String debugMessage, Integer... ids) {
154 
155         int nbParams = ids.length / 2;
156 
157         Object[] params = new Object[nbParams * 3];
158         for (int i = 0; i < nbParams; i++) {
159             Integer sortingPmfmId = ids[2 * i];
160             Integer sortingQualitativeValueId = ids[2 * i + 1];
161             params[3 * i] = CatchBatchExtendDao.PMFM_ID;
162             params[3 * i + 1] = sortingPmfmId;
163             params[3 * i + 2] = sortingQualitativeValueId;
164         }
165         SortingBatch result = catchBatchDao.getSortingBatch(childs, params);
166         if (result != null && debugMessage != null && log.isDebugEnabled()) {
167             log.debug("Loaded " + debugMessage + ": " + result.getId());
168         }
169         return result;
170     }
171 
172     protected final SortingBatch getOrCreate(CatchBatch rootBatch,
173                                              Batch batch,
174                                              String debugMessage,
175                                              Integer sortingPmfmId,
176                                              Integer sortingQualitativeValueId,
177                                              short rankOrder) {
178         return getOrCreate(rootBatch,
179                            batch,
180                            debugMessage,
181                            sortingPmfmId,
182                            sortingQualitativeValueId,
183                            null,
184                            null,
185                            rankOrder);
186     }
187 
188     protected final SortingBatch getOrCreate(CatchBatch rootBatch,
189                                              Batch batch,
190                                              String debugMessage,
191                                              Integer sortingPmfmId,
192                                              Integer sortingQualitativeValueId,
193                                              Float totalWeight,
194                                              short rankOrder) {
195         return getOrCreate(rootBatch,
196                            batch,
197                            debugMessage,
198                            sortingPmfmId,
199                            sortingQualitativeValueId,
200                            totalWeight,
201                            null,
202                            rankOrder);
203     }
204 
205     protected final SortingBatch getOrCreate(CatchBatch rootBatch,
206                                              Batch batch,
207                                              String debugMessage,
208                                              Integer sortingPmfmId,
209                                              Integer sortingQualitativeValueId,
210                                              Float weight,
211                                              Float weightBeforeSampling,
212                                              short rankOrder) {
213 
214         SortingBatch result = getSortingBatch(
215                 batch,
216                 debugMessage,
217                 sortingPmfmId,
218                 sortingQualitativeValueId);
219 
220         if (result == null) {
221 
222             result = SortingBatch.Factory.newInstance();
223             if (batch.getChildBatchs() == null) {
224                 batch.setChildBatchs(Sets.<Batch>newHashSet());
225             }
226             batch.getChildBatchs().add(result);
227 
228             // --- Some mandatory properties --- //
229 
230             QualityFlagImpl qualityFlag = load(QualityFlagImpl.class, QualityFlagCode.NOTQUALIFIED.getValue());
231             result.setQualityFlag(qualityFlag);
232             result.setRootBatch(rootBatch);
233             result.setParentBatch(batch);
234             result.setExhaustiveInventory(true);
235             result.setRankOrder(rankOrder);
236 
237             // No taxon or taxon group
238             result.setReferenceTaxon(null);
239             result.setTaxonGroup(null);
240 
241             // --- Sorting measurement --- //
242 
243             Collection<SortingMeasurement> sortingMeasurements = result.getSortingMeasurements();
244             Set<SortingMeasurement> notChangedSortingMeasurements = Sets.newHashSet();
245             if (sortingMeasurements != null) {
246                 notChangedSortingMeasurements.addAll(sortingMeasurements);
247             }
248 
249             if (sortingPmfmId != null && sortingQualitativeValueId != null) {
250                 SortingMeasurement sm = measurementPersistenceHelper.setSortingMeasurement(
251                         result,
252                         sortingPmfmId,
253                         sortingQualitativeValueId);
254                 notChangedSortingMeasurements.remove(sm);
255             }
256             if (sortingMeasurements != null) {
257                 sortingMeasurements.removeAll(notChangedSortingMeasurements);
258             }
259 
260             catchBatchDao.createSortingBatch(result, rootBatch);
261         }
262 
263         // --- Sampling Ratio + QuantificationMeasurement --- //
264 
265         setWeightAndSampleRatio(result, weight, weightBeforeSampling);
266 
267         return result;
268     }
269 
270     //------------------------------------------------------------------------//
271     //-- Debug methods                                                      --//
272     //------------------------------------------------------------------------//
273 
274     public final void displayCatchBatch(CatchBatch result) {
275         StringBuilder sb = new StringBuilder();
276         displayBatch(result, 0, sb);
277         log.info(sb.toString());
278     }
279 
280     protected final void displayBatch(Batch batch, int level, StringBuilder sb) {
281 
282         ToStringStyle style = new BatchTreeToStringStyle();
283 
284         ToStringBuilder builder = new ToStringBuilder(batch, style);
285         builder.append("id", batch.getId());
286         builder.append("rankOrder", batch.getRankOrder());
287 
288         if (batch instanceof CatchBatch) {
289             CatchBatch catchBatch = (CatchBatch) batch;
290             builder.append("synchronizationStatus", catchBatch.getSynchronizationStatus());
291         }
292         if (batch instanceof SortingBatch) {
293             SortingBatch sortingBatch = (SortingBatch) batch;
294             if (sortingBatch.getSamplingRatio() != null) {
295                 builder.append("samplingRatio", sortingBatch.getSamplingRatio());
296             }
297             if (sortingBatch.getSamplingRatioText() != null) {
298                 builder.append("samplingRatioText", sortingBatch.getSamplingRatioText());
299             }
300             if (sortingBatch.getIndividualCount() != null) {
301                 builder.append("individualCount", sortingBatch.getIndividualCount());
302             }
303             if (sortingBatch.getReferenceTaxon() != null) {
304                 ReferenceTaxon referenceTaxon = sortingBatch.getReferenceTaxon();
305                 builder.append("referenceTaxon", load(ReferenceTaxonImpl.class, referenceTaxon.getId()).getName());
306             }
307 
308             SortingMeasurement sm = null;
309             if (sortingBatch.getSortingMeasurements() != null && sortingBatch.getSortingMeasurements().size() == 1) {
310                 sm = sortingBatch.getSortingMeasurements().iterator().next();
311             } else if (sortingBatch.getReferenceTaxon() != null && sortingBatch.getReferenceTaxon().getId() != null) {
312                 sm = measurementPersistenceHelper.getInheritedSortingMeasurement(sortingBatch);
313             }
314             if (sm != null) {
315                 String sortingMeasurementStr = measurementPersistenceHelper.toString(sm);
316                 builder.append("sortingMeasurement", sortingMeasurementStr);
317             }
318         }
319         QuantificationMeasurement quantificationMeasurement = measurementPersistenceHelper.getWeightMeasurementQuantificationMeasurement(batch);
320         if (quantificationMeasurement != null) {
321             String quantificationMeasurementStr = measurementPersistenceHelper.toString(quantificationMeasurement);
322             builder.append("weightQuantificationMeasurement", quantificationMeasurementStr);
323             builder.append("weightQuantificationMeasurement.isReferenceQuantification", quantificationMeasurement.getIsReferenceQuantification());
324         }
325         if (batch.getWeight() != null) {
326             builder.append("weight", batch.getWeight());
327         }
328         if (batch.getWeightBeforeSampling() != null) {
329             builder.append("weightBeforeSampling", batch.getWeightBeforeSampling());
330         }
331         builder.append("qualityFlag", load(QualityFlagImpl.class, batch.getQualityFlag().getCode()).getName());
332 
333         String prefix = "\n" + StringUtils.leftPad("", 2 * level);
334         String batchStr = Joiner.on(prefix).join(builder.build().split("\n"));
335         sb.append(prefix).append(batchStr);
336         Collection<Batch> childBatchs = batch.getChildBatchs();
337         if (childBatchs != null) {
338             List<Batch> childBatchList = new ArrayList<>(childBatchs);
339             Collections.sort(childBatchList, batchComparator);
340             for (Batch childBatch : childBatchList) {
341                 displayBatch(childBatch, level + 1, sb);
342             }
343         }
344     }
345 
346     public final CatchBatch loadCatchBatch(Integer catchBatchId) {
347         return catchBatchDao.loadFullTreeWithCache(catchBatchId, PmfmId.WEIGHT_MEASURED.getValue(), true, true);
348     }
349 
350 
351     static final class BatchTreeToStringStyle extends ToStringStyle {
352 
353         private static final long serialVersionUID = 1L;
354 
355         BatchTreeToStringStyle() {
356             super();
357             this.setUseClassName(true);
358             this.setUseShortClassName(true);
359             this.setContentStart("");
360             this.setFieldSeparator(SystemUtils.LINE_SEPARATOR + "  | ");
361             this.setFieldSeparatorAtStart(true);
362             this.setContentEnd("");
363         }
364     }
365 }