PageRenderTime 588ms CodeModel.GetById 231ms app.highlight 117ms RepoModel.GetById 235ms app.codeStats 1ms

/src/main/java/com/google/ie/business/service/impl/ProjectServiceImpl.java

http://thoughtsite.googlecode.com/
Java | 384 lines | 236 code | 39 blank | 109 comment | 30 complexity | 1c9389f8a8d79f22c767104b71cc8d25 MD5 | raw file
  1/* Copyright 2010 Google Inc.
  2 * 
  3 * Licensed under the Apache License, Version 2.0 (the "License");
  4 * you may not use this file except in compliance with the License.
  5 * You may obtain a copy of the License at
  6 * 
  7 *      http://www.apache.org/licenses/LICENSE-2.0
  8 * 
  9 * Unless required by applicable law or agreed to in writing, software
 10 * distributed under the License is distributed on an "AS IS" BASIS.
 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 12 * See the License for the specific language governing permissions and
 13 * limitations under the License
 14 */
 15
 16package com.google.ie.business.service.impl;
 17
 18import com.google.appengine.api.datastore.Blob;
 19import com.google.ie.business.dao.ProjectDao;
 20import com.google.ie.business.domain.EntityIndex;
 21import com.google.ie.business.domain.Idea;
 22import com.google.ie.business.domain.Project;
 23import com.google.ie.business.domain.User;
 24import com.google.ie.business.service.EntityIndexService;
 25import com.google.ie.business.service.IdeaService;
 26import com.google.ie.business.service.ProjectService;
 27import com.google.ie.business.service.ServiceConstants;
 28import com.google.ie.common.audit.AuditManager;
 29import com.google.ie.common.cache.CacheConstants;
 30import com.google.ie.common.cache.CacheHelper;
 31import com.google.ie.common.constants.IdeaExchangeConstants;
 32import com.google.ie.common.constants.IdeaExchangeErrorCodes;
 33import com.google.ie.common.exception.SystemException;
 34import com.google.ie.common.taskqueue.IndexQueueUpdater;
 35import com.google.ie.dto.RetrievalInfo;
 36import com.google.ie.web.controller.WebConstants;
 37
 38import org.apache.commons.lang.StringUtils;
 39import org.apache.log4j.Logger;
 40import org.springframework.beans.factory.annotation.Autowired;
 41import org.springframework.stereotype.Service;
 42
 43import java.util.Date;
 44import java.util.HashSet;
 45import java.util.Iterator;
 46import java.util.LinkedList;
 47import java.util.List;
 48import java.util.Set;
 49
 50/**
 51 * A service implementation of the ProjectService
 52 * 
 53 * @author Charanjeet singh
 54 * 
 55 */
 56@Service
 57public class ProjectServiceImpl implements ProjectService {
 58    private static final Logger LOGGER = Logger.getLogger(ProjectServiceImpl.class);
 59    private static final int DEFAULT_NO_OF_RECENT_PROJECTS = 3;
 60    @Autowired
 61    private IdeaService ideaService;
 62    @Autowired
 63    private ProjectDao projectDao;
 64    @Autowired
 65    private AuditManager auditManager;
 66    @Autowired
 67    private EntityIndexService entityIndexService;
 68    @Autowired
 69    private IndexQueueUpdater indexQueueUpdater;
 70
 71    public IndexQueueUpdater getIndexQueueUpdater() {
 72        return indexQueueUpdater;
 73    }
 74
 75    public void setIndexQueueUpdater(IndexQueueUpdater indexQueueUpdater) {
 76        this.indexQueueUpdater = indexQueueUpdater;
 77    }
 78
 79    @Override
 80    public Project createOrUpdateProject(Project project, User user) {
 81        /* check for user and idea key. */
 82        if (StringUtils.isBlank(user.getUserKey()) || StringUtils.isBlank(project.getIdeaKey())) {
 83            throw new SystemException(IdeaExchangeErrorCodes.PROJECT_CREATION_FAILURE_EXCEPTION,
 84                            IdeaExchangeConstants.Messages.PROJECT_CREATION_FAILURE_MESSAGE);
 85        }
 86        Idea idea = ideaService.getIdeaByKey(project.getIdeaKey());
 87
 88        /*
 89         * We need to check only for saved idea as edit project is possible on
 90         * deleted idea as well
 91         */
 92        if (!idea.getStatus().equals(Idea.STATUS_SAVED)) {
 93            /* Save project details */
 94            long date = System.currentTimeMillis();
 95            /* If project already exists then update it */
 96            if (project.getKey() != null) {
 97                Project projectFromDataStore = getProjectDao().getProject(project.getKey());
 98                projectFromDataStore.setUpdatedOn(new Date(date));
 99                projectFromDataStore.setName(project.getName());
100                projectFromDataStore.setDescription(project.getDescription());
101                projectFromDataStore.setLogo(project.getLogo());
102                project = saveProjectLocal(projectFromDataStore);
103            } else {
104                /* If project is newly created */
105                project.setStatus(Project.STATUS_CREATED);
106                project.setCreatedOn(new Date(date));
107                project.setUpdatedOn(new Date(date));
108                project.setCreatorKey(user.getUserKey());
109                project = saveProjectLocal(project);
110                afterProjectCreation(project, user, idea);
111            }
112            return project;
113        }
114        return null;
115    }
116
117    /**
118     * Check validity arguments for project creation .
119     * 
120     * @throws SystemException
121     */
122    private boolean checkIfValid(Idea idea) throws SystemException {
123
124        /* Check if idea is published. */
125        if (!idea.getStatus().equals(Idea.STATUS_PUBLISHED)) {
126            throw new SystemException(
127                            IdeaExchangeErrorCodes.PROJECT_CREATION_FAILURE_UNPUBLISHED_IDEA_EXCEPTION,
128                            IdeaExchangeConstants.Messages.PROJECT_CREATION_FAILURE_UNPUBLISHED_IDEA_MESSAGE);
129        }
130        return true;
131    }
132
133    /**
134     * Save project and index it.
135     * 
136     * @param project Project to be saved
137     * @return Saved project
138     */
139    private Project saveProjectLocal(Project project) {
140        project = projectDao.saveProject(project);
141        if (project != null) {
142            /*
143             * Index the entity.Create an EntityIndex object for the entity
144             * to be indexed and then queue the job to task queue
145             */
146            EntityIndex entityIndex = entityIndexService.createEntityIndex(project.getKey());
147            getIndexQueueUpdater().indexEntity(entityIndex.getKey());
148        }
149        return project;
150    }
151
152    /**
153     * Performs the post project creation activity.
154     * 
155     * @param project Project entity.
156     * @param user The User who has created the project.
157     * @param idea Idea entity on which a project is being created.
158     * 
159     */
160    private void afterProjectCreation(Project project, User user, Idea idea) {
161        LOGGER.info("Project is successfully saved");
162        /* log the activity into Audit log. */
163        getAuditManager().audit(user.getUserKey(), project.getKey(),
164                        project.getClass().getName(),
165                        ServiceConstants.AUDIT_ACTION_TYPE_CREATE_PROJECT);
166        /* Place the idea into recently picked ideas. */
167        CacheHelper.putObject(CacheConstants.PROJECT_NAMESPACE,
168                        CacheConstants.RECENTLY_PICKED, idea);
169        addIdeaToRecentlyPickedIdeaListInCache(idea);
170    }
171
172    @SuppressWarnings("unchecked")
173    private void addIdeaToRecentlyPickedIdeaListInCache(Idea ideaToBeAdded) {
174        /* Get the list of recently picked ideas from cache */
175        LinkedList<Idea> ideas = (LinkedList<Idea>) CacheHelper.getObject(
176                        CacheConstants.IDEA_NAMESPACE,
177                        CacheConstants.RECENTLY_PICKED_IDEAS);
178        if (ideas != null) {
179            Iterator<Idea> iterator = ideas.iterator();
180            Idea ideaFromCache = null;
181            /* Iterate to check whether the list already contains the idea */
182            while (iterator.hasNext()) {
183                ideaFromCache = iterator.next();
184                String ideaKey = ideaFromCache.getKey();
185                if (ideaKey.equalsIgnoreCase(ideaToBeAdded.getKey())) {
186                    /*
187                     * If idea already exists in the list , move it to the head
188                     */
189                    ideas.remove(ideaFromCache);
190                    ideas.addFirst(ideaFromCache);
191                    CacheHelper.putObject(CacheConstants.IDEA_NAMESPACE,
192                                    CacheConstants.RECENTLY_PICKED_IDEAS, ideas,
193                                    CacheConstants.RECENTLY_PICKED_IDEAS_EXPIRATION_DELAY);
194                    return;
195                }
196            }
197        }
198        /* This is executed if the idea does not already exist in cache */
199        ideaService.addIdeaToListInCache(ideaToBeAdded, CacheConstants.RECENTLY_PICKED_IDEAS,
200                        DEFAULT_NO_OF_RECENT_PROJECTS,
201                        CacheConstants.RECENTLY_PICKED_IDEAS_EXPIRATION_DELAY);
202    }
203
204    @Override
205    public Blob getImageById(String key) {
206        Project project = projectDao.getProject(key);
207        Blob image = project.getLogo();
208        if (image == null)
209            return null;
210        return image;
211
212    }
213
214    @Override
215    public Project getDetails(Project project) {
216        if (project != null && !StringUtils.isBlank(project.getKey())) {
217            LOGGER.debug("Retrieving details for the project with key=" + project.getKey());
218            project = projectDao.getProject(project.getKey());
219
220            return project;
221        }
222        throw new SystemException(IdeaExchangeErrorCodes.PROJECT_DETAILS_EXCEPTION,
223                        IdeaExchangeConstants.Messages.PROJECT_DETAILS_EXCEPTION_MESSAGE);
224    }
225
226    @Override
227    public List<Project> listProjects(RetrievalInfo retrievalInfo) {
228        /* Fetch one more record than what is required */
229        retrievalInfo.setNoOfRecords(retrievalInfo.getNoOfRecords() + WebConstants.ONE);
230        /*
231         * Retrieve Project based on the retrieval information. If retrievalInfo
232         * object is null then use default parameter information.
233         */
234        retrievalInfo = prepareRetrievalInfoForQuery(retrievalInfo);
235        /* Prepare the Set of status */
236        Set<String> statusOfProject = new HashSet<String>();
237        statusOfProject.add(Project.STATUS_CREATED);
238
239        return getProjectDao().getProjects(retrievalInfo, statusOfProject);
240    }
241
242    @Override
243    public List<Project> listProjects(User user, RetrievalInfo retrievalInfo) {
244        /*
245         * Retrieve Project based on the retrieval information. If retrievalInfo
246         * object is null then use default parameter information.
247         */
248        retrievalInfo = prepareRetrievalInfoForQuery(retrievalInfo);
249        /* Prepare the Set of status */
250        Set<String> statusOfProject = new HashSet<String>();
251        statusOfProject.add(Project.STATUS_CREATED);
252        return getProjectDao().getProjects(user, retrievalInfo, statusOfProject);
253    }
254
255    @Override
256    public List<Project> getProjects(Set<String> projectKeys, RetrievalInfo retrievalInfo) {
257        return getProjectDao().getProjectsByKeys(projectKeys, retrievalInfo);
258    }
259
260    /**
261     * Prepares the {@link RetrievalInfo} object with values to be used as query
262     * parameters.
263     * Checks the received RetrievalInfo object attributes for valid
264     * data.Updates the attributes if they contain garbage values.If the
265     * received {@link RetrievalInfo} object is null,sets it to a new instance
266     * with its attributes set to default values.
267     * 
268     * @param retrievalInfo the {@link RetrievalInfo} object containing the
269     *        values to be used as query parameters
270     * @return the {@link RetrievalInfo} object containing the query parameters
271     */
272
273    private RetrievalInfo prepareRetrievalInfoForQuery(RetrievalInfo retrievalInfo) {
274        if (retrievalInfo == null) {
275            retrievalInfo = new RetrievalInfo();
276            retrievalInfo.setStartIndex(ServiceConstants.ZERO);
277            retrievalInfo.setNoOfRecords(ServiceConstants.PROJECT_LIST_DEFAULT_SIZE);
278            retrievalInfo.setOrderType(ServiceConstants.PROJECT_DEFAULT_ORDERING_TYPE);
279            retrievalInfo.setOrderBy(ServiceConstants.DEFAULT_PROJECT_ORDERING_FIELD);
280        } else {
281            // Handle garbage values if any.
282            String orderOn = retrievalInfo.getOrderBy();
283            String orderByParam = retrievalInfo.getOrderType();
284            if (retrievalInfo.getStartIndex() < ServiceConstants.ZERO)
285                retrievalInfo.setStartIndex(ServiceConstants.ZERO);
286            if (retrievalInfo.getNoOfRecords() <= ServiceConstants.ZERO)
287                retrievalInfo.setNoOfRecords(ServiceConstants.PROJECT_LIST_DEFAULT_SIZE);
288            if (orderByParam == null || !((orderByParam.equals(ServiceConstants.ORDERING_ASCENDING)
289                            || orderByParam.equals(ServiceConstants.ORDERING_DESCENDING))))
290                retrievalInfo.setOrderType(ServiceConstants.PROJECT_DEFAULT_ORDERING_TYPE);
291            if (orderOn == null
292                            || !orderOn.equals(ServiceConstants.PROJECT_ORDERING_FIELD_UPDATED_ON)) {
293                retrievalInfo.setOrderBy(ServiceConstants.DEFAULT_PROJECT_ORDERING_FIELD);
294            }
295        }
296        return retrievalInfo;
297    }
298
299    @Override
300    public List<Project> getProjectsByIdeaKey(String key) {
301        return getProjectDao().getProjectsByIdeaKey(key);
302    }
303
304    /**
305     * @param ideaService the ideaService to set
306     */
307    public void setIdeaService(IdeaService ideaService) {
308        this.ideaService = ideaService;
309    }
310
311    /**
312     * @return the ideaService
313     */
314    public IdeaService getIdeaService() {
315        return ideaService;
316    }
317
318    /**
319     * @param projectDao the projectDao to set
320     */
321    public void setProjectDao(ProjectDao projectDao) {
322        this.projectDao = projectDao;
323    }
324
325    /**
326     * @return the projectDao
327     */
328    public ProjectDao getProjectDao() {
329        return projectDao;
330    }
331
332    /**
333     * @param auditManager the auditManager to set
334     */
335    public void setAuditManager(AuditManager auditManager) {
336        this.auditManager = auditManager;
337    }
338
339    /**
340     * @return the auditManager
341     */
342    public AuditManager getAuditManager() {
343        return auditManager;
344    }
345
346    /**
347     * @return the entityIndexService
348     */
349    public EntityIndexService getEntityIndexService() {
350        return entityIndexService;
351    }
352
353    /**
354     * @param entityIndexService the entityIndexService to set
355     */
356    public void setEntityIndexService(EntityIndexService entityIndexService) {
357        this.entityIndexService = entityIndexService;
358    }
359
360    @Override
361    public Project getProjectById(String key) {
362        return projectDao.findEntityByPrimaryKey(Project.class, key);
363
364    }
365
366    @Override
367    public List<Project> getRecentProjects() {
368        RetrievalInfo retrievalInfo = new RetrievalInfo();
369        retrievalInfo.setNoOfRecords(DEFAULT_NO_OF_RECENT_PROJECTS);
370        retrievalInfo.setOrderBy(Project.PROJECT_FIELD_CREATED_ON);
371        retrievalInfo.setOrderType(ServiceConstants.ORDERING_DESCENDING);
372        /* The set of status to match for */
373        Set<String> statusOfProject = new HashSet<String>();
374        statusOfProject.add(Project.STATUS_CREATED);
375        return projectDao.getProjects(retrievalInfo, statusOfProject);
376    }
377
378    @Override
379    public Project updateProject(Project project) {
380        return projectDao.saveProject(project);
381    }
382
383}
384