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