View Javadoc
1   /*
2    * #%L
3    * Coser :: Web
4    * %%
5    * Copyright (C) 2012 Ifremer, Codelutin, Chatellier Eric, Chemit Tony
6    * %%
7    * This program is free software: you can redistribute it and/or modify
8    * it under the terms of the GNU Affero General Public License as published by
9    * the Free Software Foundation, either version 3 of the License, or
10   * (at your option) any later version.
11   * 
12   * This program is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   * GNU General Public License for more details.
16   * 
17   * You should have received a copy of the GNU Affero General Public License
18   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19   * #L%
20   */
21  
22  package fr.ifremer.coser.web.actions.search;
23  
24  import com.google.common.collect.Lists;
25  import fr.ifremer.coser.result.request.ExtractRawDataAndResultsRequest;
26  import fr.ifremer.coser.result.request.GetIndicatorsForExtractRawDataAndResultsRequest;
27  import fr.ifremer.coser.result.request.GetSpeciesForExtractRawDataAndResultsRequest;
28  import fr.ifremer.coser.result.request.GetZonesForExtractRawDataAndResultsRequest;
29  import fr.ifremer.coser.result.result.FileResult;
30  import fr.ifremer.coser.util.DataType;
31  import fr.ifremer.coser.web.actions.common.AbstractCoserJspAction;
32  import org.apache.commons.collections4.CollectionUtils;
33  import org.apache.commons.lang3.StringUtils;
34  import org.apache.struts2.convention.annotation.Action;
35  import org.apache.struts2.convention.annotation.InterceptorRef;
36  import org.apache.struts2.convention.annotation.InterceptorRefs;
37  import org.apache.struts2.convention.annotation.Result;
38  import org.apache.struts2.interceptor.ServletRequestAware;
39  
40  import javax.servlet.http.HttpServletRequest;
41  import java.io.InputStream;
42  import java.util.List;
43  import java.util.Locale;
44  import java.util.Map;
45  
46  /**
47   * Affiche le formulaire de recherche pour extraction d'un zip contenant
48   * les sources des projets choisit, et un pdf avec les graphiques et les données
49   * des graphiques.
50   *
51   * @author echatellier
52   * @since 1.4
53   */
54  @InterceptorRefs({
55                           @InterceptorRef("defaultStack"),
56                           @InterceptorRef(value = "execAndWait",
57                                           params = {"excludeMethods", "execute,quality"})
58                   })
59  public class ExtractAction extends AbstractCoserJspAction implements ServletRequestAware {
60  
61      /** serialVersionUID. */
62      private static final long serialVersionUID = 8497086194191374797L;
63  
64      public static final String DOWNLOAD = "download";
65  
66      public static final String LOCALE_ATTRIBUTE = "locale";
67  
68      protected Map<String, String> zones;
69  
70      protected Map<String, String> types;
71  
72      protected List<String> selectZones;
73  
74      protected List<DataType> selectTypes;
75  
76      protected Map<String, String> species;
77  
78      protected List<String> selectSpecies;
79  
80      protected Map<String, String> comIndicators;
81  
82      protected List<String> selectComIndicators;
83  
84      protected Map<String, String> popIndicators;
85  
86      protected List<String> selectPopIndicators;
87  
88      protected String submitAction;
89  
90      protected boolean accepted;
91  
92      //FIXME Should only use the struts2 session ?
93      protected transient HttpServletRequest servletRequest;
94  
95      protected FileResult resultFile;
96  
97      public Map<String, String> getZones() {
98          return zones;
99      }
100 
101     public List<String> getSelectZones() {
102         return selectZones;
103     }
104 
105     public void setSelectZones(List<String> selectZones) {
106         this.selectZones = selectZones;
107     }
108 
109     public Map<String, String> getTypes() {
110         return types;
111     }
112 
113     public List<DataType> getSelectTypes() {
114         return selectTypes;
115     }
116 
117     public void setSelectTypes(List<DataType> selectTypes) {
118         this.selectTypes = selectTypes;
119     }
120 
121     public List<String> getSelectSpecies() {
122         return selectSpecies;
123     }
124 
125     public void setSelectSpecies(List<String> selectSpecies) {
126         this.selectSpecies = selectSpecies;
127     }
128 
129     public List<String> getSelectComIndicators() {
130         return selectComIndicators;
131     }
132 
133     public void setSelectComIndicators(List<String> selectComIndicators) {
134         this.selectComIndicators = selectComIndicators;
135     }
136 
137     public List<String> getSelectPopIndicators() {
138         return selectPopIndicators;
139     }
140 
141     public void setSelectPopIndicators(List<String> selectPopIndicators) {
142         this.selectPopIndicators = selectPopIndicators;
143     }
144 
145     public Map<String, String> getSpecies() {
146         return species;
147     }
148 
149     public Map<String, String> getComIndicators() {
150         return comIndicators;
151     }
152 
153     public Map<String, String> getPopIndicators() {
154         return popIndicators;
155     }
156 
157     public void setSubmitAction(String submitAction) {
158         this.submitAction = submitAction;
159     }
160 
161     // used by validation
162     public boolean isAccepted() {
163         return accepted;
164     }
165 
166     public void setAccepted(boolean accepted) {
167         this.accepted = accepted;
168     }
169 
170     /**
171      * Pour le hack du execute and wait.
172      * On met des choses dans la session pour pouvoir les récupérer.
173      */
174     @Override
175     public void setServletRequest(HttpServletRequest servletrequest) {
176         this.servletRequest = servletrequest;
177     }
178 
179     @Override
180     public String execute() {
181 
182         String result;
183 
184         if (StringUtils.isNotBlank(submitAction)) {
185             result = SUCCESS;
186         } else {
187             result = INPUT;
188 
189             types = DataType.getExtractTypes(getLocale());
190 
191             // renvoi la liste des id subzone-survey et leurs label associé
192             GetZonesForExtractRawDataAndResultsRequest zonesRequest =
193                     requestBuilder(GetZonesForExtractRawDataAndResultsRequest.class).
194                             toRequest();
195             zones = getService().toMap(zonesRequest);
196 
197             if (CollectionUtils.isNotEmpty(selectZones)) {
198 
199                 GetSpeciesForExtractRawDataAndResultsRequest speciesRequest =
200                         requestBuilder(GetSpeciesForExtractRawDataAndResultsRequest.class).
201                                 addZoneList(selectZones).
202                                 addExtractTypeList(selectTypes).
203                                 toRequest();
204                 species = getService().toMap(speciesRequest);
205 
206                 if (selectTypes != null) {
207 
208                     GetIndicatorsForExtractRawDataAndResultsRequest indicatorsRequest =
209                             requestBuilder(GetIndicatorsForExtractRawDataAndResultsRequest.class).
210                                     addZoneList(selectZones).
211                                     toRequest();
212 
213                     if (selectTypes.contains(DataType.COMMUNITY)) {
214 
215                         indicatorsRequest.setExtractTypeList(Lists.newArrayList(DataType.COMMUNITY));
216                         comIndicators = getService().toMap(indicatorsRequest);
217                     }
218 
219                     if (selectTypes.contains(DataType.POPULATION)) {
220                         indicatorsRequest.setExtractTypeList(Lists.newArrayList(DataType.POPULATION));
221                         popIndicators = getService().toMap(indicatorsRequest);
222                     }
223                 }
224             }
225         }
226 
227         return result;
228     }
229 
230     @Action(value = "extract-quality",
231             results = {
232                     @Result(name = "input", location = "/WEB-INF/content/search/extract-success.jsp"),
233                     @Result(name = DOWNLOAD, type = "redirect", params = {"location", "${location}"})})
234     public String quality() {
235         // petit hack pour mettre la locale dans la session car
236         // après, on n'a plus accès au context dans le executeAndWait
237         servletRequest.getSession().setAttribute(LOCALE_ATTRIBUTE, getLocale());
238         return DOWNLOAD;
239     }
240 
241     /**
242      * C'est super dur des faire une redirection sur une url.
243      * Construction d'une url complete.
244      *
245      * @return l'url de redirection
246      */
247     public String getLocation() {
248         String url = "extract-download?accepted=true";
249         if (selectZones != null) {
250             for (String zone : selectZones) {
251                 url += "&selectZones=" + zone;
252             }
253         }
254         if (selectTypes != null) {
255             for (DataType type : selectTypes) {
256                 url += "&selectTypes=" + type;
257             }
258         }
259         if (selectSpecies != null) {
260             for (String species : selectSpecies) {
261                 url += "&selectSpecies=" + species;
262             }
263         }
264         if (selectComIndicators != null) {
265             for (String selectComIndicator : selectComIndicators) {
266                 url += "&selectComIndicators=" + selectComIndicator;
267             }
268         }
269         if (selectPopIndicators != null) {
270             for (String selectPopIndicator : selectPopIndicators) {
271                 url += "&selectPopIndicators=" + selectPopIndicator;
272             }
273         }
274         return url;
275     }
276 
277     @Action(value = "extract-download",
278             results = {
279                     @Result(name = "wait", location = "/WEB-INF/content/search/extract-wait.jsp"),
280                     @Result(type = "stream", params = {"contentType", "application/zip", "contentDisposition", "attachment; filename=\"${filename}\""})})
281     public String download() {
282 
283         Locale locale = (Locale) servletRequest.getSession().getAttribute(LOCALE_ATTRIBUTE);
284 
285         ExtractRawDataAndResultsRequest request =
286                 requestBuilder(locale, ExtractRawDataAndResultsRequest.class).
287                         addZoneList(selectZones).
288                         addExtractTypeList(selectTypes).
289                         addSpeciesList(selectSpecies).
290                         addCommunityIndicatorList(selectComIndicators).
291                         addPopulationIndicatorList(selectPopIndicators).
292                         toRequest();
293 
294         resultFile = getService().extractRawDataAndResults(locale, request);
295         return SUCCESS;
296     }
297 
298     public InputStream getInputStream() {
299         InputStream is = resultFile.getInputStream();
300         return is;
301     }
302 
303     public String getFilename() {
304         return "Indicateurs_Ifremer.zip";
305     }
306 
307     //    @Action(value = "extract-quality",
308 //            results = {
309 //                    @Result(location = "/WEB-INF/content/search/extract-success.jsp"),
310 //                    @Result(name = DOWNLOAD, type = "redirect", params = {
311 //                            "location", "${location}"})})
312 //    public String quality() {
313 //        String result;
314 //        if (!accepted) {
315 //            addFieldError("accepted", getText("message.quality.notaccepted"));
316 //            result = SUCCESS;
317 //        } else {
318 //
319 //            // petit hack pour mettre la locale dans la session car
320 //            // après, on n'a plus accès au context dans le executeAndWait
321 //            request.getSession().setAttribute("locale", getLocale());
322 //            result = DOWNLOAD;
323 //        }
324 //        return result;
325 //    }
326 //
327 //    protected File zipFile;
328 //
329 //    @Override
330 //    public String execute() {
331 //
332 //        String result;
333 //
334 //        if (StringUtils.isNotBlank(submitAction)) {
335 //            result = SUCCESS;
336 //        } else {
337 //            result = INPUT;
338 //            Locale locale = getLocale();
339 //            WebService webService = ServiceFactory.getWebService();
340 //
341 //            try {
342 //                // renvoi la liste des id subzone-survey et leurs label associé
343 //                zones = webService.getZoneForFacade(null, false, false);
344 //                if (CollectionUtils.isNotEmpty(selectZones)) {
345 //                    species = webService.getSpecies(selectZones, false);
346 //
347 //                    if (selectTypes != null && selectTypes.contains(DataType.COMMUNITY)) {
348 //                        comIndicators = webService.getIndicators(selectZones, DataType.COMMUNITY, locale);
349 //                    }
350 //                    if (selectTypes != null && selectTypes.contains(DataType.POPULATION)) {
351 //                        popIndicators = webService.getIndicators(selectZones, DataType.POPULATION, locale);
352 //                    }
353 //                }
354 //            } catch (CoserBusinessException ex) {
355 //                throw new CoserWebException("Can't get zone map", ex);
356 //            }
357 //        }
358 //
359 //        return result;
360 //    }
361 //
362 //    public String download() {
363 //        try {
364 //            Locale locale = (Locale)request.getSession().getAttribute("locale");
365 //            WebService webService = ServiceFactory.getWebService();
366 //
367 //            zipFile = webService.extractData(selectZones, selectTypes, selectSpecies,
368 //                    selectComIndicators, selectPopIndicators, locale);
369 //        } catch (Exception ex) {
370 //            if (log.isErrorEnabled()) {
371 //                log.error("Can't extract data", ex);
372 //            }
373 //            throw new CoserWebException("Can't extract data", ex);
374 //        }
375 //        return "success";
376 //    }
377 //
378 //    public InputStream getInputStream() {
379 //    InputStream is = null;
380 //    try {
381 //        is = new FileInputStream(zipFile);
382 //    } catch (Exception ex) {
383 //        if (log.isErrorEnabled()) {
384 //            log.error("Can't extract data", ex);
385 //        }
386 //        throw new CoserWebException("Can't extract data", ex);
387 //    }
388 //    return is;
389 //}
390 }