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.ProgramCode;
28  import fr.ifremer.adagio.core.dao.administration.programStrategy.ProgramDao;
29  import fr.ifremer.adagio.core.dao.referential.gear.GearClassificationId;
30  import fr.ifremer.adagio.core.dao.referential.gear.GearClassificationImpl;
31  import fr.ifremer.adagio.core.dao.referential.location.Location;
32  import fr.ifremer.adagio.core.dao.referential.location.LocationClassificationId;
33  import fr.ifremer.adagio.core.dao.referential.location.LocationDao;
34  import fr.ifremer.adagio.core.dao.referential.location.LocationLevelId;
35  import fr.ifremer.adagio.core.dao.referential.taxon.TaxonGroupTypeCode;
36  import fr.ifremer.adagio.core.dao.referential.taxon.TaxonGroupTypeImpl;
37  import fr.ifremer.tutti.persistence.entities.data.Program;
38  import fr.ifremer.tutti.persistence.entities.data.Programs;
39  import fr.ifremer.tutti.persistence.entities.referential.TuttiLocation;
40  import fr.ifremer.tutti.persistence.entities.referential.TuttiLocations;
41  import org.apache.commons.logging.Log;
42  import org.apache.commons.logging.LogFactory;
43  import org.hibernate.type.IntegerType;
44  import org.hibernate.type.StringType;
45  import org.springframework.dao.DataRetrievalFailureException;
46  import org.springframework.stereotype.Service;
47  
48  import javax.annotation.Resource;
49  import java.util.Collections;
50  import java.util.Iterator;
51  import java.util.List;
52  
53  /**
54   * @author Tony Chemit - chemit@codelutin.com
55   * @since 0.3
56   */
57  @Service("programPersistenceService")
58  public class ProgramPersistenceServiceImpl extends AbstractPersistenceService implements ProgramPersistenceService {
59  
60      /** Logger. */
61      private static final Log log =
62              LogFactory.getLog(ProgramPersistenceServiceImpl.class);
63  
64      @Resource(name = "programDao")
65      protected ProgramDao programDao;
66  
67      @Resource(name = "locationDao")
68      protected LocationDao locationDao;
69  
70      protected final int maxCodeLengthInDatabase = 40;
71  
72      @Override
73      public List<Program> getAllProgram() {
74          String codePattern = "%";
75          if (ProgramCode.SCIENTIFIC_CRUISE_PREFIX.getValue() != null) {
76              codePattern = ProgramCode.SCIENTIFIC_CRUISE_PREFIX.getValue() + codePattern;
77          }
78          Iterator<Object[]> list = queryList(
79                  "allPrograms",
80                  "codePattern", StringType.INSTANCE, codePattern,
81                  "locationLevelId", IntegerType.INSTANCE, LocationLevelId.SCIENTIFIC_CRUISE_PROGRAM.getValue(),
82                  "locationClassificationId", IntegerType.INSTANCE, LocationClassificationId.SECTOR.getValue()
83          );
84  
85          List<Program> result = Lists.newArrayList();
86          while (list.hasNext()) {
87              Object[] source = list.next();
88              Program target = Programs.newProgram();
89              loadProgram(target, source);
90              result.add(target);
91          }
92          return Collections.unmodifiableList(result);
93      }
94  
95      @Override
96      public Program getProgram(String id) {
97          Iterator<Object[]> list = queryList(
98                  "program",
99                  "programCode", StringType.INSTANCE, id,
100                 "locationLevelId", IntegerType.INSTANCE, LocationLevelId.SCIENTIFIC_CRUISE_PROGRAM.getValue(),
101                 "locationClassificationId", IntegerType.INSTANCE, LocationClassificationId.SECTOR.getValue());
102 
103         Program result;
104 
105         if (list.hasNext()) {
106 
107             // Keep only the first row (=the first location, if many found)
108             Object[] source = list.next();
109 
110             result = Programs.newProgram();
111             loadProgram(result, source);
112         } else {
113             result = null;
114         }
115         return result;
116     }
117 
118     @Override
119     public Program createProgram(Program bean) {
120         Preconditions.checkNotNull(bean);
121         Preconditions.checkNotNull(bean.getName());
122         Preconditions.checkNotNull(bean.getDescription());
123         Preconditions.checkArgument(bean.getId() == null);
124 
125         if (log.isDebugEnabled()) {
126             log.debug("Create program with name: " + bean.getName());
127         }
128         fr.ifremer.adagio.core.dao.administration.programStrategy.Program program = fr.ifremer.adagio.core.dao.administration.programStrategy.Program.Factory.newInstance();
129         programToEntity(bean, program);
130         program = programDao.create(program);
131         bean.setId(String.valueOf(program.getCode()));
132 
133         return bean;
134     }
135 
136     @Override
137     public Program saveProgram(Program bean) {
138         Preconditions.checkNotNull(bean);
139         Preconditions.checkNotNull(bean.getName());
140         Preconditions.checkNotNull(bean.getId());
141         Preconditions.checkNotNull(bean.getDescription());
142 
143         if (log.isDebugEnabled()) {
144             log.debug("Save program with name: " + bean.getName());
145         }
146         fr.ifremer.adagio.core.dao.administration.programStrategy.Program program = programDao.load(bean.getId());
147         if (program == null) {
148             throw new DataRetrievalFailureException("Could not retrieve program with code=" + bean.getId());
149         }
150 
151         programToEntity(bean, program);
152         programDao.update(program);
153 
154         return bean;
155     }
156 
157     // ------------------------------------------------------------------------//
158     // -- Internal methods --//
159     // ------------------------------------------------------------------------//
160 
161     protected void loadProgram(Program result, Object[] source) {
162         result.setId((String) source[0]);
163         result.setName((String) source[1]);
164         result.setDescription((String) source[2]);
165         if (source[3] != null) {
166             TuttiLocation zone = TuttiLocations.newTuttiLocation();
167             zone.setId(String.valueOf(source[3]));
168             zone.setLabel((String) source[4]);
169             zone.setName((String) source[5]);
170             result.setZone(zone);
171         }
172     }
173 
174     protected void programToEntity(Program source,
175                                    fr.ifremer.adagio.core.dao.administration.programStrategy.Program target) {
176         // Code : compute with : <prefixe><name>
177         if (target.getCode() == null && source.getName() != null) {
178             // Compute a program code (remove spaces, and capitalize the name)
179             String programCode = source.getName().toUpperCase().replaceAll(" ", "_");
180             // Add a prefix
181             if (ProgramCode.SCIENTIFIC_CRUISE_PREFIX.getValue() != null) {
182                 programCode = ProgramCode.SCIENTIFIC_CRUISE_PREFIX.getValue() + programCode;
183             }
184             // Trunc the code if too long 
185             if (programCode.length() > maxCodeLengthInDatabase) {
186                 programCode = programCode.substring(0, maxCodeLengthInDatabase - 1);
187             }
188             target.setCode(programCode);
189 
190             // Mandatory properties :
191             // Gear classification :
192             target.setGearClassification(load(GearClassificationImpl.class, GearClassificationId.SCIENTIFIC_CRUISE.getValue()));
193 
194             // taxon group type
195             target.setTaxonGroupType(load(TaxonGroupTypeImpl.class, TaxonGroupTypeCode.COMMERCIAL_SPECIES.getValue()));
196 
197             // Creation date
198             target.setCreationDate(newCreateDate());
199         }
200 
201         // Name (mandatory in database)
202         target.setName(source.getName());
203 
204         // Description (mandatory in database)
205         target.setDescription(source.getDescription());
206 
207         // Zone 
208         if (source.getZone() == null) {
209             // Remove program location classifications :
210             if (target.getLocationClassifications() != null) {
211                 target.getLocationClassifications().clear();
212             }
213             // Remove program locations :
214             if (target.getLocations() != null) {
215                 target.getLocations().clear();
216             }
217         } else if (source.getZone() != null && source.getZone().getId() != null) {
218             Location location = locationDao.load(Integer.valueOf(source.getZone().getId()));
219 
220             // Program location classifications :
221             if (target.getLocationClassifications() == null) {
222                 target.setLocationClassifications(Lists.newArrayList(location.getLocationClassification()));
223             } else {
224                 target.getLocationClassifications().clear();
225                 target.getLocationClassifications().add(location.getLocationClassification());
226             }
227 
228             // Program locations :
229             if (target.getLocations() == null) {
230                 target.setLocations(Lists.newArrayList(location));
231             } else {
232                 target.getLocations().clear();
233                 target.getLocations().add(location);
234             }
235         }
236     }
237 
238 //    public int getProgramNameMaxLength() {
239 //        int maxCodeLengthInDatabase = 40;
240 //        if (ProgramCode.SCIENTIFIC_CRUISE_PREFIX.getValue() == null
241 //            || ProgramCode.SCIENTIFIC_CRUISE_PREFIX.getValue().trim().isEmpty()) {
242 //            return maxCodeLengthInDatabase;
243 //        }
244 //        return (maxCodeLengthInDatabase - ProgramCode.SCIENTIFIC_CRUISE_PREFIX.getValue().length());
245 //    }
246 }