View Javadoc
1   package fr.ifremer.tutti.service.genericformat;
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.Preconditions;
26  import fr.ifremer.tutti.persistence.ProgressionModel;
27  import fr.ifremer.tutti.persistence.entities.data.Cruise;
28  import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
29  import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol;
30  import fr.ifremer.tutti.persistence.model.CruiseDataModel;
31  import fr.ifremer.tutti.persistence.model.ProgramDataModel;
32  import fr.ifremer.tutti.service.AbstractTuttiService;
33  import fr.ifremer.tutti.service.DecoratorService;
34  import fr.ifremer.tutti.service.PersistenceService;
35  import fr.ifremer.tutti.service.TuttiServiceContext;
36  import fr.ifremer.tutti.service.catches.WeightComputingService;
37  import fr.ifremer.tutti.service.genericformat.csv.SampleCategoryModel;
38  import fr.ifremer.tutti.service.genericformat.csv.SampleCategoryRow;
39  import fr.ifremer.tutti.service.genericformat.producer.CsvProducerForSampleCategory;
40  import org.nuiton.decorator.Decorator;
41  import org.nuiton.jaxx.application.ApplicationTechnicalException;
42  
43  import java.io.File;
44  import java.io.IOException;
45  import java.nio.file.Files;
46  import java.nio.file.Path;
47  import java.nio.file.StandardCopyOption;
48  import java.util.ArrayList;
49  import java.util.List;
50  import java.util.Set;
51  
52  import static org.nuiton.i18n.I18n.t;
53  
54  /**
55   * To export data in the generic format.
56   *
57   * See http://forge.codelutin.com/issues/1875.
58   *
59   * @author Tony Chemit - chemit@codelutin.com
60   * @since 1.3
61   */
62  public class GenericFormatExportService extends AbstractTuttiService {
63  
64      private PersistenceService persistenceService;
65  
66      private WeightComputingService weightComputingService;
67  
68      private GenericFormatExportActionEngine actionEngine;
69  
70      private Decorator<FishingOperation> fishingOperationDecorator;
71  
72      @Override
73      public void setServiceContext(TuttiServiceContext context) {
74  
75          super.setServiceContext(context);
76  
77          this.persistenceService = getService(PersistenceService.class);
78          this.weightComputingService = getService(WeightComputingService.class);
79          this.actionEngine = new GenericFormatExportActionEngine(context);
80  
81          DecoratorService decoratorService = getService(DecoratorService.class);
82          this.fishingOperationDecorator = decoratorService.getDecoratorByType(FishingOperation.class);
83  
84      }
85  
86      public int getExportNbSteps(GenericFormatExportConfiguration configuration) {
87  
88          ProgramDataModel dataToExport = configuration.getDataToExport();
89  
90          int result = 8; // export species + sampleCategoryModel + protocol + temporary gear + temporary person + temporar species +  temporary vessel + zip
91          for (CruiseDataModel cruise : dataToExport) {
92              int nbFishingOperations = cruise.size();
93              result += getCruiseNbStep(nbFishingOperations);
94          }
95  
96          return result;
97  
98      }
99  
100     public GenericFormatExportResult export(GenericFormatExportConfiguration configuration, ProgressionModel progressionModel) {
101 
102         Preconditions.checkNotNull(configuration);
103         Preconditions.checkNotNull(progressionModel);
104 
105         GenericFormatExportRequest exportRequest = createExportRequest(configuration);
106 
107         List<String> errors = new ArrayList<>();
108 
109         try (GenericFormatExportContext exportContext = createExportContext(exportRequest, progressionModel)) {
110 
111             actionEngine.executeLoadActions(exportContext);
112 
113             for (GenericFormatExportCruiseContext cruiseContext : exportContext) {
114 
115                 Cruise cruise = cruiseContext.getCruise();
116 
117                 Set<FishingOperation> operations = cruiseContext.getOperations();
118 
119                 String checkErrors = cruiseContext.getCheckErrors();
120                 if (checkErrors != null) {
121                     errors.add(checkErrors);
122                 }
123 
124                 exportCruise(exportContext, cruise, operations);
125             }
126 
127             actionEngine.executeTechnicalActions(exportContext);
128 
129             return new GenericFormatExportResult(exportRequest, errors);
130 
131         }
132 
133     }
134 
135 
136     /**
137      * Export the sample category model as a csv file used for generic format import-export.
138      *
139      * @param exportFile where to export sample category model
140      * @since 3.14
141      */
142     public void exportSampleCategoryModel(File exportFile) throws IOException {
143 
144         ProgressionModel progressionModel = new ProgressionModel();
145         progressionModel.setTotal(1000);
146 
147         GenericFormatArchive archive = GenericFormatArchive.forExport(null, context.getConfig().getTmpDirectory());
148 
149         try (CsvProducerForSampleCategory producerForSampleCategory = new CsvProducerForSampleCategory(archive.getSampleCategoryModelPath(), SampleCategoryModel.forExport(';'))) {
150 
151             List<SampleCategoryRow> dataToExport = producerForSampleCategory.getDataToExport(context.getSampleCategoryModel());
152 
153             try {
154                 producerForSampleCategory.write(dataToExport);
155             } catch (Exception e) {
156                 throw new ApplicationTechnicalException("Could not export sample category model", e);
157             }
158         }
159 
160         try {
161             Files.copy(archive.getSampleCategoryModelPath(), exportFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
162         } catch (IOException e) {
163             throw new ApplicationTechnicalException("Could not copy csv file to export file", e);
164         }
165 
166     }
167 
168     protected GenericFormatExportRequest createExportRequest(GenericFormatExportConfiguration configuration) {
169 
170         Path attachmentsSourcePath = context.getConfig().getDbAttachmentDirectory().toPath();
171 
172         TuttiProtocol tuttiProtocol = context.getDataContext().getProtocol();
173 
174         GenericFormatArchive archive = GenericFormatArchive.forExport(configuration.getExportFile(), context.getConfig().getTmpDirectory());
175 
176         return new GenericFormatExportRequest(configuration,
177                                               archive,
178                                               ';',
179                                               context.getSampleCategoryModel(),
180                                               tuttiProtocol,
181                                               context.getConfig().getExportCountryId(),
182                                               attachmentsSourcePath
183         );
184 
185     }
186 
187     protected GenericFormatExportContext createExportContext(GenericFormatExportRequest exportRequest, ProgressionModel progressionModel) {
188 
189         return new GenericFormatExportContext(progressionModel,
190                                               exportRequest,
191                                               persistenceService,
192                                               fishingOperationDecorator);
193 
194     }
195 
196     protected void exportCruise(GenericFormatExportContext exportContext, Cruise cruise, Set<FishingOperation> operations) {
197 
198         actionEngine.executeCruiseActions(exportContext, cruise);
199 
200         for (FishingOperation operation : operations) {
201 
202             GenericFormatExportOperationContext operationContext = exportContext.newOperationContext(persistenceService, weightComputingService, cruise, operation);
203             exportContext.increments(t("tutti.service.genericFormat.exportCruise.exportOperation", cruise.getName(), operationContext.getOperationLabel()));
204 
205             actionEngine.executeOperationActions(exportContext, operationContext);
206 
207         }
208 
209     }
210 
211     protected int getCruiseNbStep(int nbFishingOperations) {
212 
213         return 1 + nbFishingOperations // check cruise + operations
214                      + 1 // export cruise
215                      + 1 // export gear caracteristics
216                      + nbFishingOperations;
217 
218     }
219 
220 }