View Javadoc
1   package fr.ifremer.dali.dao.referential.monitoringLocation;
2   
3   /*
4    * #%L
5    * Dali :: Core
6    * $Id:$
7    * $HeadURL:$
8    * %%
9    * Copyright (C) 2014 - 2015 Ifremer
10   * %%
11   * This program is free software: you can redistribute it and/or modify
12   * it under the terms of the GNU Affero General Public License as published by
13   * the Free Software Foundation, either version 3 of the License, or
14   * (at your option) any later version.
15   *
16   * This program is distributed in the hope that it will be useful,
17   * but WITHOUT ANY WARRANTY; without even the implied warranty of
18   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19   * GNU General Public License for more details.
20   *
21   * You should have received a copy of the GNU Affero General Public License
22   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23   * #L%
24   */
25  
26  import com.google.common.collect.ImmutableList;
27  import fr.ifremer.dali.config.DaliConfiguration;
28  import fr.ifremer.dali.dao.referential.DaliReferentialDao;
29  import fr.ifremer.dali.dao.referential.transcribing.DaliTranscribingItemDao;
30  import fr.ifremer.dali.dao.technical.Daos;
31  import fr.ifremer.dali.dao.technical.Geometries;
32  import fr.ifremer.dali.dto.DaliBeanFactory;
33  import fr.ifremer.dali.dto.referential.HarbourDTO;
34  import fr.ifremer.dali.dto.referential.LocationDTO;
35  import fr.ifremer.quadrige3.core.dao.referential.monitoringLocation.MonitoringLocationDaoImpl;
36  import fr.ifremer.quadrige3.core.service.technical.CacheService;
37  import org.apache.commons.collections4.CollectionUtils;
38  import org.apache.commons.lang3.StringUtils;
39  import org.hibernate.SessionFactory;
40  import org.hibernate.type.IntegerType;
41  import org.hibernate.type.StringType;
42  import org.springframework.beans.factory.annotation.Autowired;
43  import org.springframework.cache.Cache;
44  import org.springframework.dao.DataRetrievalFailureException;
45  import org.springframework.stereotype.Repository;
46  
47  import javax.annotation.Resource;
48  import java.util.*;
49  import java.util.function.Predicate;
50  import java.util.stream.Collectors;
51  
52  /**
53   * <p>DaliMonitoringLocationDaoImpl class.</p>
54   */
55  @Repository("daliMonitoringLocationDao")
56  public class DaliMonitoringLocationDaoImpl extends MonitoringLocationDaoImpl implements DaliMonitoringLocationDao {
57  
58      @Resource
59      protected DaliConfiguration config;
60  
61      @Resource
62      protected CacheService cacheService;
63  
64      @Resource(name = "daliReferentialDao")
65      private DaliReferentialDao referentialDao;
66  
67      @Resource(name = "daliTranscribingItemDao")
68      private DaliTranscribingItemDao transcribingItemDao;
69  
70      @Resource(name = "daliMonitoringLocationDao")
71      private DaliMonitoringLocationDao loopbackDao;
72  
73      /**
74       * <p>Constructor for DaliMonitoringLocationDaoImpl.</p>
75       *
76       * @param sessionFactory a {@link org.hibernate.SessionFactory} object.
77       */
78      @Autowired
79      public DaliMonitoringLocationDaoImpl(SessionFactory sessionFactory) {
80          super(sessionFactory);
81      }
82  
83      /**
84       * {@inheritDoc}
85       */
86      @Override
87      public List<LocationDTO> getLocationsByCampaignAndProgram(Integer campaignId, String programCode) {
88  
89          Iterator<Object[]> it;
90          if (campaignId == null) {
91              it = queryIterator("monitoringLocationsByProgramCode",
92                  "programCode", StringType.INSTANCE, programCode);
93          } else {
94              it = queryIterator("monitoringLocationsByCampaignIdAndProgramCode",
95                  "programCode", StringType.INSTANCE, programCode,
96                  "campaignId", IntegerType.INSTANCE, campaignId);
97          }
98  
99          List<LocationDTO> result = new ArrayList<>();
100         Map<Integer, String> transcribingNamesById = getTranscribingNames();
101 
102         while (it.hasNext()) {
103             Object[] row = it.next();
104             result.add(toLocationDTO(Arrays.asList(row).iterator(), transcribingNamesById));
105         }
106 
107         return ImmutableList.copyOf(result);
108     }
109 
110     /**
111      * {@inheritDoc}
112      *
113      * @param locationIds
114      */
115     @Override
116     @SuppressWarnings("unchecked")
117     public List<LocationDTO> getLocationsByIds(List<Integer> locationIds) {
118 
119         List<LocationDTO> result = new ArrayList<>();
120         if (CollectionUtils.isEmpty(locationIds))
121             return result;
122 
123         Iterator<Object[]> it = createQuery("monitoringLocationsByIds")
124             .setParameterList("locationIds", locationIds)
125             .iterate();
126 
127         Map<Integer, String> transcribingNamesById = getTranscribingNames();
128 
129         while (it.hasNext()) {
130             Object[] row = it.next();
131             result.add(toLocationDTO(Arrays.asList(row).iterator(), transcribingNamesById));
132         }
133 
134         return result;
135 
136     }
137 
138     /**
139      * {@inheritDoc}
140      */
141     @Override
142     public List<LocationDTO> getAllLocations(List<String> statusCodes) {
143 
144         Cache cacheById = cacheService.getCache(LOCATION_BY_ID_CACHE);
145 
146         Iterator<Object[]> it = Daos.queryIteratorWithStatus(createQuery("allMonitoringLocations"), statusCodes);
147 
148         List<LocationDTO> result = new ArrayList<>();
149         Map<Integer, String> transcribingNamesById = getTranscribingNames();
150 
151         while (it.hasNext()) {
152             Object[] row = it.next();
153             LocationDTO location = toLocationDTO(Arrays.asList(row).iterator(), transcribingNamesById);
154             result.add(location);
155             cacheById.put(location.getId(), location);
156         }
157 
158         return ImmutableList.copyOf(result);
159     }
160 
161     /**
162      * {@inheritDoc}
163      */
164     @Override
165     public LocationDTO getLocationById(int locationId) {
166 
167         Object[] row = queryUnique("monitoringLocationById", "monitoringLocationId", IntegerType.INSTANCE, locationId);
168 
169         if (row == null) {
170             throw new DataRetrievalFailureException("can't load monitoring location with id = " + locationId);
171         }
172 
173         return toLocationDTO(Arrays.asList(row).iterator(), getTranscribingNames());
174     }
175 
176     /**
177      * {@inheritDoc}
178      */
179     @Override
180     public List<LocationDTO> findLocations(List<String> statusCodes, String orderItemTypeCode, Integer orderItemId, String programCode, String label, String name, boolean isStrictName) {
181 
182         List<LocationDTO> result = loopbackDao.getAllLocations(statusCodes);
183         Predicate<LocationDTO> filter = location -> true;
184 
185         // Predicate on grouping type
186         if (orderItemTypeCode != null || orderItemId != null) {
187             List<Integer> locationIds = getLocationIdsByOrderItem(orderItemTypeCode, orderItemId);
188             filter = filter.and(location -> locationIds.contains(location.getId()));
189         }
190 
191         // Predicate on program
192         if (programCode != null) {
193             List<Integer> locationIds = loopbackDao.getLocationsByCampaignAndProgram(null, programCode).stream().map(LocationDTO::getId).collect(Collectors.toList());
194             filter = filter.and(location -> locationIds.contains(location.getId()));
195         }
196 
197         // Predicate on label
198         if (label != null)
199             filter = filter.and(location -> location.getLabel().toLowerCase().contains(label.toLowerCase()));
200 
201         // Predicate on name after transcribing (Mantis #49923)
202         if (name != null)
203             filter = filter.and(location -> isStrictName ? location.getName().equalsIgnoreCase(name) : location.getName().toLowerCase().contains(name.toLowerCase()));
204 
205         // Filter
206         result = result.stream().filter(filter).collect(Collectors.toList());
207 
208         return ImmutableList.copyOf(result);
209 
210     }
211 
212     /**
213      * {@inheritDoc}
214      */
215     @Override
216     public List<HarbourDTO> getAllHarbours(List<String> statusCodes) {
217 
218         Iterator<Object[]> it = Daos.queryIteratorWithStatus(createQuery("allHarbours"), statusCodes);
219 
220         List<HarbourDTO> result = new ArrayList<>();
221         while (it.hasNext()) {
222             Object[] row = it.next();
223             result.add(toHarbourDTO(Arrays.asList(row).iterator()));
224         }
225 
226         return result;
227     }
228 
229     // INTERNAL METHODS
230 
231     private List<Integer> getLocationIdsByOrderItem(String orderItemTypeCode, Integer orderItemId) {
232         return queryListTyped("monitoringLocationIdsByOrderItem",
233             "orderItemTypeCode", StringType.INSTANCE, orderItemTypeCode,
234             "orderItemId", IntegerType.INSTANCE, orderItemId
235         );
236     }
237 
238     private Map<Integer, String> getTranscribingNames() {
239         return transcribingItemDao.getAllTranscribingItemsById(config.getTranscribingItemTypeLbForMonLocNm());
240     }
241 
242     private LocationDTO toLocationDTO(Iterator<Object> source, Map<Integer, String> transcribingNamesById) {
243         LocationDTO result = DaliBeanFactory.newLocationDTO();
244         result.setId((Integer) source.next());
245         result.setName((String) source.next());
246         result.setBathymetry(Daos.convertToDouble((Float) source.next()));
247         result.setComment((String) source.next());
248         result.setLabel((String) source.next());
249         result.setUtFormat((Double) source.next());
250         result.setDayLightSavingTime(Daos.convertToBoolean(source.next()));
251         HarbourDTO harbour = toHarbourDTO(source);
252         result.setHarbour(StringUtils.isNotBlank(harbour.getCode()) ? harbour : null);
253         result.setStatus(referentialDao.getStatusByCode((String) source.next()));
254         result.setPositioning(referentialDao.getPositioningSystemById((Integer) source.next()));
255         result.setCoordinate(Geometries.getCoordinate((String) source.next()));
256         result.setCreationDate(Daos.convertToDate(source.next()));
257         result.setUpdateDate(Daos.convertToDate(source.next()));
258 
259         // transcribed name (Mantis #47219)
260         result.setName(transcribingNamesById.getOrDefault(result.getId(), result.getName()));
261 
262         return result;
263     }
264 
265     private HarbourDTO toHarbourDTO(Iterator<Object> source) {
266         HarbourDTO result = DaliBeanFactory.newHarbourDTO();
267         result.setCode((String) source.next());
268         result.setName((String) source.next());
269         return result;
270     }
271 
272 }