View Javadoc
1   package fr.ifremer.tutti.service.export.sumatra;
2   
3   /*
4    * #%L
5    * Tutti :: Service
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.Charsets;
26  import com.google.common.base.Preconditions;
27  import com.google.common.collect.Lists;
28  import com.google.common.io.Files;
29  import fr.ifremer.tutti.persistence.ProgressionModel;
30  import fr.ifremer.tutti.persistence.entities.data.Cruise;
31  import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
32  import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol;
33  import fr.ifremer.tutti.persistence.entities.referential.Species;
34  import fr.ifremer.tutti.persistence.entities.referential.TaxonCache;
35  import fr.ifremer.tutti.persistence.entities.referential.TaxonCaches;
36  import fr.ifremer.tutti.service.AbstractTuttiService;
37  import fr.ifremer.tutti.service.PersistenceService;
38  import fr.ifremer.tutti.service.TuttiServiceContext;
39  import fr.ifremer.tutti.service.catches.WeightComputingService;
40  import fr.ifremer.tutti.service.export.ExportBatchEntry;
41  import fr.ifremer.tutti.service.export.ExportCatchContext;
42  import org.apache.commons.io.IOUtils;
43  import org.apache.commons.lang3.StringUtils;
44  import org.apache.commons.logging.Log;
45  import org.apache.commons.logging.LogFactory;
46  import org.nuiton.csv.Export;
47  import org.nuiton.jaxx.application.ApplicationTechnicalException;
48  
49  import java.io.BufferedWriter;
50  import java.io.File;
51  import java.util.HashSet;
52  import java.util.List;
53  import java.util.Set;
54  
55  import static org.nuiton.i18n.I18n.t;
56  
57  /**
58   * @author Kevin Morin - kmorin@codelutin.com
59   * @since 2.0
60   */
61  public class CatchesSumatraExportService extends AbstractTuttiService {
62  
63      private static final Log log =
64              LogFactory.getLog(CatchesSumatraExportService.class);
65  
66      protected PersistenceService persistenceService;
67  
68      protected WeightComputingService weightComputingService;
69  
70      @Override
71      public void setServiceContext(TuttiServiceContext context) {
72          super.setServiceContext(context);
73          persistenceService = getService(PersistenceService.class);
74          weightComputingService = getService(WeightComputingService.class);
75      }
76  
77      /**
78       * Export selected cruise with the csv sumatra format.
79       *
80       * @param file     where to generate report
81       * @param cruiseId id of the cruise to export
82       * @return export result
83       * @since 2.0
84       */
85      public SumatraExportResult exportCruiseForSumatra(File file,
86                                                        Integer cruiseId,
87                                                        ProgressionModel progressionModel) {
88  
89          Preconditions.checkNotNull(cruiseId, "Cannot export a null cruise");
90          Preconditions.checkNotNull(file, "Cannot export to a null file");
91  
92          if (log.isInfoEnabled()) {
93              log.info("Will export cruise " + cruiseId + " to file: " + file);
94          }
95  
96          progressionModel.increments(t("tutti.service.sumatra.export.step.load.cruise", cruiseId));
97  
98          Cruise cruise = persistenceService.getCruise(cruiseId);
99          Preconditions.checkNotNull(cruise, "Cruise [" + cruiseId + "] not found");
100 
101         progressionModel.increments(t("tutti.service.sumatra.export.step.load.fishingOperationIds"));
102 
103         List<Integer> operations =
104                 persistenceService.getAllFishingOperationIds(cruiseId);
105 
106         if (log.isInfoEnabled()) {
107             log.info(operations.size() + " operations found for cruise: " + cruiseId);
108         }
109 
110         progressionModel.adaptTotal(operations.size() + 3);
111 
112         SumatraExportResult result = new SumatraExportResult();
113 
114         prepareOperationsAndExport(file, operations, progressionModel, result);
115 
116         return result;
117     }
118 
119     /**
120      * Export selected fishing operation with the csv sumatra format.
121      *
122      * @param file               where to generate report
123      * @param cruiseId           id of the cruise to export
124      * @param fishingOperationId id of the fishing operation to export
125      * @return export result
126      * @since 2.7
127      */
128     public SumatraExportResult exportFishingOperationForSumatra(File file,
129                                                                 Integer cruiseId,
130                                                                 Integer fishingOperationId,
131                                                                 ProgressionModel progressionModel) {
132 
133         Preconditions.checkNotNull(file, "Cannot export to a null file");
134         Preconditions.checkNotNull(cruiseId, "Cannot export a null cruise");
135         Preconditions.checkNotNull(fishingOperationId, "Cannot export a null fishing operation");
136 
137         if (log.isInfoEnabled()) {
138             log.info("Will export fishing operation " +
139                      fishingOperationId + " to file: " + file);
140         }
141 
142         progressionModel.increments(t("tutti.service.sumatra.export.step.load.cruise", cruiseId));
143 
144         Cruise cruise = persistenceService.getCruise(cruiseId);
145         Preconditions.checkNotNull(cruise, "Cruise [" + cruiseId + "] not found");
146 
147         List<Integer> operations = Lists.newArrayList(fishingOperationId);
148 
149         SumatraExportResult result = new SumatraExportResult();
150 
151         prepareOperationsAndExport(file, operations, progressionModel, result);
152 
153         return result;
154     }
155 
156     protected void prepareOperationsAndExport(File file,
157                                               List<Integer> operations,
158                                               ProgressionModel progressionModel,
159                                               SumatraExportResult result) {
160 
161         List<CatchRow> rows = Lists.newArrayList();
162 
163         CatchRowModel csvModel =
164                 new CatchRowModel(context.getConfig().getCsvSeparator());
165 
166         if (operations != null) {
167 
168             TuttiProtocol protocol = context.getDataContext().getProtocol();
169 
170             TaxonCache speciesCache = TaxonCaches.createSpeciesCacheWithoutVernacularCode(persistenceService, protocol);
171             TaxonCache benthosCache = TaxonCaches.createBenthosCacheWithoutVernacularCode(persistenceService, protocol);
172 
173             for (Integer operationId : operations) {
174 
175                 progressionModel.increments(t("tutti.service.sumatra.export.step.load.fishingOperation", operationId));
176                 if (!persistenceService.isFishingOperationWithCatchBatch(operationId)) {
177 
178                     if (log.isWarnEnabled()) {
179                         log.warn("No catch for operation with id: " + operationId);
180                     }
181                     break;
182                 }
183 
184                 prepareFishingOperation(speciesCache, benthosCache, csvModel, rows, operationId, result);
185 
186             }
187         }
188 
189         progressionModel.increments(t("tutti.service.sumatra.export.step.export", file));
190 
191         BufferedWriter writer = null;
192         try {
193             writer = Files.newWriter(file, Charsets.UTF_8);
194             Export export = Export.newExport(csvModel, rows);
195             export.write(writer);
196             writer.close();
197 
198         } catch (Exception e) {
199             throw new ApplicationTechnicalException(t("tutti.service.sumatra.export.error", file), e);
200         } finally {
201             IOUtils.closeQuietly(writer);
202         }
203     }
204 
205     protected void prepareFishingOperation(TaxonCache speciesCache,
206                                            TaxonCache benthosCache,
207                                            CatchRowModel csvModel,
208                                            List<CatchRow> rows,
209                                            Integer operationId,
210                                            SumatraExportResult result) {
211 
212         ExportCatchContext exportContext = ExportCatchContext.newExportContext(
213                 persistenceService,
214                 weightComputingService,
215                 operationId,
216                 true);
217 
218         FishingOperation operation = exportContext.getFishingOperation();
219 
220         // Species
221         if (exportContext.withSpeciesBatches()) {
222 
223             List<ExportBatchEntry> entries = exportContext.getSpeciesBatchEntry(true);
224             Set<String> badSpecies = prepareFishingOperationSpecies(speciesCache, entries, csvModel, rows, operation);
225             result.setBadSpecies(badSpecies);
226 
227         }
228 
229         // Benthos
230         if (exportContext.withBenthosBatches()) {
231 
232             List<ExportBatchEntry> entries = exportContext.getBenthosBatchEntry(true);
233             Set<String> badBenthos = prepareFishingOperationBenthos(benthosCache, entries, csvModel, rows, operation);
234             result.setBadBenthos(badBenthos);
235 
236         }
237     }
238 
239     protected Set<String> prepareFishingOperationSpecies(TaxonCache taxonCache,
240                                                          List<ExportBatchEntry> entries,
241                                                          CatchRowModel csvModel,
242                                                          List<CatchRow> rows,
243                                                          FishingOperation operation) {
244 
245         Set<String> badSpecies = new HashSet<>();
246 
247         for (ExportBatchEntry entry : entries) {
248 
249             Species species = entry.getBatch().getSpecies();
250 
251             // load species codes
252             taxonCache.load(species);
253 
254             if (StringUtils.isBlank(species.getSurveyCode())) {
255                 badSpecies.add(species.getName());
256             }
257 
258             CatchRow row = csvModel.newRow(operation, entry);
259 
260             rows.add(row);
261 
262         }
263 
264         return badSpecies;
265 
266     }
267 
268     protected Set<String> prepareFishingOperationBenthos(TaxonCache taxonCache,
269                                                          List<ExportBatchEntry> entries,
270                                                          CatchRowModel csvModel,
271                                                          List<CatchRow> rows,
272                                                          FishingOperation operation) {
273 
274         Set<String> badBenthos = new HashSet<>();
275 
276         for (ExportBatchEntry entry : entries) {
277 
278             Species species = entry.getBatch().getSpecies();
279 
280             // load species codes
281             taxonCache.load(species);
282             if (StringUtils.isBlank(species.getSurveyCode())) {
283                 badBenthos.add(species.getName());
284             }
285 
286             CatchRow row = csvModel.newRow(operation, entry);
287             rows.add(row);
288 
289         }
290 
291         return badBenthos;
292 
293     }
294 
295 
296 }