View Javadoc
1   package fr.ifremer.dali.dao.system.context;
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.Lists;
27  import com.google.common.collect.Sets;
28  import fr.ifremer.dali.dto.DaliBeanFactory;
29  import fr.ifremer.dali.dto.DaliBeans;
30  import fr.ifremer.dali.dto.configuration.context.ContextDTO;
31  import fr.ifremer.quadrige3.core.dao.referential.Status;
32  import fr.ifremer.quadrige3.core.dao.referential.StatusCode;
33  import fr.ifremer.quadrige3.core.dao.referential.StatusImpl;
34  import fr.ifremer.quadrige3.core.dao.system.context.Context;
35  import fr.ifremer.quadrige3.core.dao.system.context.ContextDaoImpl;
36  import fr.ifremer.quadrige3.core.dao.system.filter.Filter;
37  import fr.ifremer.quadrige3.core.dao.system.filter.FilterImpl;
38  import fr.ifremer.quadrige3.core.dao.technical.Assert;
39  import fr.ifremer.quadrige3.core.service.technical.CacheService;
40  import org.apache.commons.collections4.CollectionUtils;
41  import org.apache.commons.lang3.StringUtils;
42  import org.hibernate.SessionFactory;
43  import org.hibernate.type.IntegerType;
44  import org.hibernate.type.StringType;
45  import org.springframework.beans.factory.annotation.Autowired;
46  import org.springframework.cache.Cache;
47  import org.springframework.dao.DataIntegrityViolationException;
48  import org.springframework.dao.DataRetrievalFailureException;
49  import org.springframework.stereotype.Repository;
50  
51  import javax.annotation.Resource;
52  import java.util.Arrays;
53  import java.util.Collection;
54  import java.util.Iterator;
55  import java.util.List;
56  
57  /**
58   * <p>DaliContextDaoImpl class.</p>
59   *
60   * @author Ludovic
61   */
62  @Repository("daliContextDao")
63  public class DaliContextDaoImpl extends ContextDaoImpl implements DaliContextDao {
64  
65      @Resource
66      protected CacheService cacheService;
67  
68      /**
69       * <p>Constructor for DaliContextDaoImpl.</p>
70       *
71       * @param sessionFactory a {@link org.hibernate.SessionFactory} object.
72       */
73      @Autowired
74      public DaliContextDaoImpl(SessionFactory sessionFactory) {
75          super(sessionFactory);
76      }
77  
78      /** {@inheritDoc} */
79      @Override
80      public List<ContextDTO> getAllContext() {
81  
82          // TODO why temp status ?
83  
84          Cache cacheById = cacheService.getCache(CONTEXT_BY_ID_CACHE);
85          Iterator<Object[]> it = queryIterator("allContext",
86                  "statusCode", StringType.INSTANCE, StatusCode.LOCAL_ENABLE.getValue());
87  
88          List<ContextDTO> result = Lists.newArrayList();
89          while (it.hasNext()) {
90              Object[] row = it.next();
91              ContextDTO context = toContextDTO(Arrays.asList(row).iterator());
92              result.add(context);
93              cacheById.put(context.getId(), context);
94          }
95  
96          return result;
97      }
98  
99      /** {@inheritDoc} */
100     @Override
101     public ContextDTO getContextById(Integer contextId) {
102         Assert.notNull(contextId);
103 
104         Object[] row = queryUnique("contextById",
105                 "contextId", IntegerType.INSTANCE, contextId,
106                 "statusCode", StringType.INSTANCE, StatusCode.LOCAL_ENABLE.getValue());
107 
108         if (row == null) {
109             throw new DataRetrievalFailureException("can't load local context with id = " + contextId);
110         }
111 
112         return toContextDTO(Arrays.asList(row).iterator());
113     }
114 
115     /** {@inheritDoc} */
116     @Override
117     public void saveContext(ContextDTO context) {
118 
119         Context entity;
120         Long contextCount = queryCount("countContextsByName", "contextName", StringType.INSTANCE, context.getName());
121         if (context.getId() == null) {
122             // check context name unicity
123             if (contextCount > 0) {
124                 throw new DataIntegrityViolationException("A context already exists with the name: " + context.getName());
125             } else {
126                 entity = create(beanToEntity(context));
127             }
128         } else {
129             entity = get(context.getId());
130             // name
131             if (StringUtils.isNotEmpty(context.getName()) && !context.getName().equals(entity.getContextNm())) {
132                 // check context name unicity
133                 if (contextCount > 0) {
134                     throw new DataIntegrityViolationException("A context already exists with the name: " + context.getName());
135                 } else {
136                     entity.setContextNm(context.getName());
137                 }
138             }
139 
140             // description
141             if (StringUtils.isNotEmpty(context.getDescription())) {
142                 entity.setContextDc(context.getDescription());
143             }
144 
145             // filters
146             if (CollectionUtils.isNotEmpty(context.getFilters())) {
147                 List<Integer> filterIds = DaliBeans.collectIds(context.getFilters());
148 
149                 Collection<Filter> filters = entity.getFilters();
150                 if (filters == null) {
151                     filters = Sets.newHashSet();
152                     entity.setFilters(filters);
153                 } else {
154                     // clear old records
155                     filters.clear();
156                 }
157 
158                 for (Integer filterId : filterIds) {
159                     Filter f = (Filter) getSession().get(FilterImpl.class, filterId);
160                     filters.add(f);
161                 }
162             }
163 
164         }
165 
166         getSession().saveOrUpdate(entity);
167         // TODO make sure unused filters are removed
168 
169         context.setId(entity.getContextId());
170 
171         getSession().flush();
172         getSession().clear();
173 
174     }
175 
176     /** {@inheritDoc} */
177     @Override
178     public void deleteContexts(List<Integer> contextIds) {
179 
180         if (CollectionUtils.isEmpty(contextIds)) {
181             return;
182         }
183 
184         createQuery("deleteContexts").setParameterList("contextIds", contextIds).executeUpdate();
185         getSession().flush();
186         getSession().clear();
187     }
188     
189     /* internal methods */
190 
191     private ContextDTO toContextDTO(Iterator<Object> source) {
192         ContextDTO result = DaliBeanFactory.newContextDTO();
193         result.setId((Integer) source.next());
194         result.setName((String) source.next());
195         result.setDescription((String) source.next());
196         // TODO-EIS set status (String) source.next()
197         return result;
198     }
199 
200     private Context beanToEntity(ContextDTO context) {
201         Context entity = Context.Factory.newInstance();
202         entity.setContextNm(context.getName());
203         entity.setContextDc(context.getDescription());
204         entity.setStatus((Status) getSession().get(StatusImpl.class, StatusCode.LOCAL_ENABLE.getValue()));
205         // TODO creation date, quser  ...
206 
207         List<Integer> filterIds = DaliBeans.collectIds(context.getFilters());
208         for (Integer filterId : filterIds) {
209             Filter filter = (Filter) getSession().get(FilterImpl.class, filterId);
210             entity.addFilters(filter);
211         }
212 
213         return entity;
214     }
215 
216 }