View Javadoc
1   package fr.ifremer.quadrige3.core.dao.data.survey;
2   
3   /*-
4    * #%L
5    * Quadrige3 Core :: Quadrige3 Client Core
6    * $Id:$
7    * $HeadURL:$
8    * %%
9    * Copyright (C) 2017 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 fr.ifremer.quadrige3.core.dao.administration.user.DepartmentImpl;
27  import fr.ifremer.quadrige3.core.dao.administration.user.QuserImpl;
28  import fr.ifremer.quadrige3.core.dao.technical.Assert;
29  import fr.ifremer.quadrige3.core.dao.technical.Beans;
30  import fr.ifremer.quadrige3.core.dao.technical.Daos;
31  import fr.ifremer.quadrige3.core.exception.QuadrigeTechnicalException;
32  import fr.ifremer.quadrige3.core.vo.data.survey.CampaignVO;
33  import fr.ifremer.quadrige3.core.vo.data.survey.OccasionVO;
34  import org.apache.commons.collections4.CollectionUtils;
35  import org.apache.commons.lang3.ArrayUtils;
36  import org.hibernate.HibernateException;
37  import org.hibernate.SessionFactory;
38  import org.hibernate.type.IntegerType;
39  import org.springframework.beans.factory.annotation.Autowired;
40  import org.springframework.context.annotation.Lazy;
41  import org.springframework.stereotype.Repository;
42  
43  import javax.annotation.Resource;
44  import java.util.Collection;
45  import java.util.List;
46  
47  /**
48   * <p>
49   * CampaignDaoImpl class.
50   * </p>
51   *
52   * @see fr.ifremer.quadrige3.core.dao.data.survey.Campaign
53   */
54  @Repository("campaignDao")
55  @Lazy
56  public class CampaignDaoImpl
57          extends CampaignDaoBase {
58      @Resource
59      private OccasionDao occasionDao;
60  
61      /**
62       * Constructor used by Spring
63       *
64       * @param sessionFactory a {@link org.hibernate.SessionFactory} object.
65       */
66      @Autowired
67      public CampaignDaoImpl(SessionFactory sessionFactory) {
68          super();
69          setSessionFactory(sessionFactory);
70      }
71  
72      @Override
73      public void remove(Collection<Campaign> entities) {
74          Assert.notEmpty(entities);
75  
76          for (Campaign entity : entities) {
77              remove(entity);
78          }
79      }
80  
81      /**
82       * {@inheritDoc}
83       */
84      @Override
85      public void remove(Campaign entity) {
86  
87          // Remove occasions
88          if (CollectionUtils.isNotEmpty(entity.getOccasions())) {
89              occasionDao.remove(entity.getOccasions());
90              entity.getOccasions().clear();
91          }
92  
93          getSession().flush();
94  
95          // Remove link to program
96          if (CollectionUtils.isNotEmpty(entity.getPrograms())) {
97              entity.getPrograms().clear();
98          }
99  
100         // Remove link to moratorium
101         if (CollectionUtils.isNotEmpty(entity.getMoratoria())) {
102             entity.getMoratoria().clear();
103         }
104 
105         super.remove(entity);
106     }
107 
108     @Override
109     protected CampaignVO handleSave(CampaignVO source) {
110 
111         Assert.notNull(source.getQuserId());
112         Assert.notNull(source.getRecDepId());
113         Assert.notNull(source.getCampaignStartDt());
114         Assert.notNull(source.getCampaignNm());
115 
116         // Already saved
117         Campaign entity = null;
118         if (source.getCampaignId() != null) {
119             entity = get(source.getCampaignId());
120         }
121 
122         // Load (or create) the entity
123         boolean isNew = false;
124         if (entity == null) {
125             entity = Campaign.Factory.newInstance();
126             isNew = true;
127         }
128 
129         // Check update_dt
130         // NOT NEED on a client database
131 
132         // Update update_dt
133         // NOT NEED on a client database
134 
135         // VO -> Entity
136         campaignVOToEntity(source, entity, true, false /* do not convert occasions */);
137 
138         // Save entity
139         if (isNew) {
140             Integer campaignId = (Integer) getSession().save(entity);
141             source.setCampaignId(campaignId);
142         } else {
143             getSession().update(entity);
144         }
145 
146         List<Integer> occasionsIdsToRemove = Beans.collectProperties(entity.getOccasions(), "occasId");
147 
148         // Save occasions
149         if (ArrayUtils.isNotEmpty(source.getOccasionVOs())) {
150             for (OccasionVO occasionVO : source.getOccasionVOs()) {
151                 occasionVO.setCampaignId(entity.getCampaignId());
152                 occasionVO = occasionDao.save(occasionVO, null);
153 
154                 occasionsIdsToRemove.remove(occasionVO.getOccasId());
155             }
156         }
157 
158         getSession().flush();
159         getSession().clear();
160 
161         // remove unused occasions
162         if (CollectionUtils.isNotEmpty(occasionsIdsToRemove)) {
163             occasionDao.removeByIds(occasionsIdsToRemove);
164         }
165 
166         return source;
167     }
168 
169     @Override
170     protected Long handleCountSurveyUsage(int campaignId) {
171         try
172         {
173             return queryCount("countSurveyUsingCampaign",
174                     "campaignId", IntegerType.INSTANCE, campaignId);
175 
176         } catch (HibernateException he) {
177             throw new QuadrigeTechnicalException(String.format("Could not get the campaign usage in surveys : %s", he.getMessage()), he);
178         }
179     }
180 
181     /*
182     @Override
183     protected Integer[] handleGetWritableCampaignIdsByUserId(Integer quserId) throws Exception {
184 
185         // Get writable programs for user
186         List<ProgramVO> writablePrograms = programStrategyJdbcDao.getWritableProgramsByUserId(quserId);
187 
188         try {
189 
190             Query query = createQuery("writableCampaignIdsByQuserId",
191                     "quserId", IntegerType.INSTANCE, quserId);
192 
193             // Limit to active users
194             query.setParameterList("statusCodes", ImmutableList.of(StatusCode.ENABLE.getValue()));
195 
196             // Writable programs for user (if any)
197             if (CollectionUtils.isEmpty(writablePrograms)) {
198                 query.setParameter("progCds", null);
199                 query.setParameter("hasProgCds", null);
200             } else {
201                 query.setParameterList("progCds", Lists.transform(writablePrograms, ProgramVO::getProgCd));
202                 query.setParameter("hasProgCds", true);
203             }
204 
205             List<Integer> campaignIds = (List<Integer>) query.list();
206 
207             return campaignIds.toArray(new Integer[campaignIds.size()]);
208 
209         } catch (HibernateException he) {
210             throw new QuadrigeTechnicalException(String.format("Could not get the writable campaign Ids for user: %s", he.getMessage()));
211         }
212     }
213 */
214     @Override
215     public void toCampaignVO(Campaign source, CampaignVO target) {
216 
217         // copy base attributes
218         super.toCampaignVO(source, target);
219 
220         // copy user and recorder department attributes
221         target.setQuserId(source.getQuser() != null ? source.getQuser().getQuserId() : null);
222         target.setRecDepId(source.getRecorderDepartment() != null ? source.getRecorderDepartment().getDepId() : null);
223 
224         // Occasions
225         if (CollectionUtils.isEmpty(source.getOccasions())) {
226             target.setOccasionVOs(null);
227         } else {
228             target.setOccasionVOs(occasionDao.toOccasionVOArray(source.getOccasions()));
229         }
230     }
231 
232     /**
233      * Retrieves the entity object that is associated with the specified value object
234      * from the object store. If no such entity object exists in the object store,
235      * a new, blank entity is created
236      */
237     private Campaign loadCampaignFromCampaignVO(CampaignVO campaignVO) {
238         Campaign campaign = null;
239         if (campaignVO.getCampaignId() != null) {
240             campaign = get(campaignVO.getCampaignId());
241         }
242         if (campaign == null) {
243             campaign = Campaign.Factory.newInstance();
244         }
245         return campaign;
246     }
247 
248     @Override
249     public Campaign campaignVOToEntity(CampaignVO campaignVO) {
250 
251         Campaign campaign = loadCampaignFromCampaignVO(campaignVO);
252         campaignVOToEntity(campaignVO, campaign, true);
253         return campaign;
254     }
255 
256     @Override
257     public void campaignVOToEntity(CampaignVO source, Campaign target, boolean copyIfNull) {
258 
259         campaignVOToEntity(source, target, copyIfNull, false);
260 
261     }
262 
263     protected void campaignVOToEntity(CampaignVO source, Campaign target, boolean copyIfNull, boolean withOccasions) {
264 
265         // copy base attributes
266         super.campaignVOToEntity(source, target, copyIfNull);
267 
268         // campaign id
269         if (copyIfNull || source.getCampaignId() != null) {
270             target.setCampaignId(source.getCampaignId());
271         }
272 
273         // quser
274         if (copyIfNull || source.getQuserId() != null) {
275             target.setQuser(source.getQuserId() != null ? load(QuserImpl.class, source.getQuserId()) : null);
276         }
277 
278         // recorder department
279         if (copyIfNull || source.getRecDepId() != null) {
280             target.setRecorderDepartment(source.getRecDepId() != null ? load(DepartmentImpl.class, source.getRecDepId()) : null);
281         }
282 
283         // Strategies
284         if (withOccasions) {
285             // Save linked occasions
286             fillEntityOccasions(source, target, copyIfNull);
287         }
288     }
289 
290     /**
291      * <p>
292      * fil occasion linked with campaign.
293      * </p>
294      *
295      * @param source     a {@link fr.ifremer.quadrige3.core.vo.data.survey.CampaignVO} object.
296      * @param target     a {@link fr.ifremer.quadrige3.core.dao.data.survey.Campaign} object.
297      * @param copyIfNull a boolean.
298      */
299     protected void fillEntityOccasions(CampaignVO source, final Campaign target, boolean copyIfNull) {
300         if (copyIfNull || source.getOccasionVOs() != null) {
301             if (source.getOccasionVOs() == null) {
302                 target.getOccasions().clear();
303             } else {
304                 Daos.replaceEntities(target.getOccasions(),
305                         source.getOccasionVOs(),
306                         occasionVO -> {
307                             Occasion occasion = occasionDao.occasionVOToEntity(occasionVO);
308                             occasion.setCampaign(target);
309                             return occasion;
310                         });
311             }
312         }
313     }
314 
315 }