PageRenderTime 93ms CodeModel.GetById 54ms app.highlight 32ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/com/google/ie/web/controller/ProjectController.java

http://thoughtsite.googlecode.com/
Java | 694 lines | 459 code | 36 blank | 199 comment | 118 complexity | e4f0b8a8638baae4319374c57cd5e615 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.web.controller;
 17
 18import static com.google.ie.web.controller.WebConstants.ERROR;
 19import static com.google.ie.web.controller.WebConstants.SUCCESS;
 20import static com.google.ie.web.controller.WebConstants.VIEW_STATUS;
 21
 22import com.google.appengine.api.datastore.Blob;
 23import com.google.ie.business.domain.Developer;
 24import com.google.ie.business.domain.Idea;
 25import com.google.ie.business.domain.Project;
 26import com.google.ie.business.domain.User;
 27import com.google.ie.business.service.DeveloperService;
 28import com.google.ie.business.service.IdeaService;
 29import com.google.ie.business.service.ProjectService;
 30import com.google.ie.business.service.UserService;
 31import com.google.ie.common.builder.ProjectBuilder;
 32import com.google.ie.common.editor.StringEditor;
 33import com.google.ie.common.email.EmailManager;
 34import com.google.ie.common.util.ReCaptchaUtility;
 35import com.google.ie.dto.ProjectDetail;
 36import com.google.ie.dto.RetrievalInfo;
 37import com.google.ie.dto.ViewStatus;
 38
 39import org.apache.commons.lang.StringUtils;
 40import org.apache.log4j.Logger;
 41import org.springframework.beans.factory.annotation.Autowired;
 42import org.springframework.beans.factory.annotation.Qualifier;
 43import org.springframework.beans.propertyeditors.CustomBooleanEditor;
 44import org.springframework.stereotype.Controller;
 45import org.springframework.ui.Model;
 46import org.springframework.validation.BindingResult;
 47import org.springframework.validation.Validator;
 48import org.springframework.web.bind.WebDataBinder;
 49import org.springframework.web.bind.annotation.InitBinder;
 50import org.springframework.web.bind.annotation.ModelAttribute;
 51import org.springframework.web.bind.annotation.PathVariable;
 52import org.springframework.web.bind.annotation.RequestMapping;
 53import org.springframework.web.bind.annotation.RequestMethod;
 54import org.springframework.web.bind.annotation.RequestParam;
 55import org.springframework.web.bind.annotation.SessionAttributes;
 56import org.springframework.web.multipart.MultipartFile;
 57
 58import java.io.IOException;
 59import java.util.ArrayList;
 60import java.util.HashMap;
 61import java.util.HashSet;
 62import java.util.Iterator;
 63import java.util.List;
 64import java.util.Map;
 65import java.util.Set;
 66
 67import javax.servlet.http.HttpServletRequest;
 68import javax.servlet.http.HttpSession;
 69
 70/**
 71 * A controller that handles request for Project entities.
 72 * 
 73 * @author Charanjeet singh
 74 * 
 75 */
 76@Controller
 77@RequestMapping("/projects")
 78@SessionAttributes("user")
 79public class ProjectController {
 80    private static Logger logger = Logger.getLogger(ProjectController.class);
 81    private static final String PROJECT_EMAIL_TYPE_INVITE_TO_JOIN = "joinProject";
 82    private static final String SEMICOLON = ";";
 83    private static final String NAME = "name";
 84    private static final String EMAILID = "emailId";
 85    @Autowired
 86    private ProjectService projectService;
 87    @Autowired
 88    private ProjectBuilder projectBuilder;
 89
 90    @Autowired
 91    private IdeaService ideaService;
 92    @Autowired
 93    private DeveloperService developerService;
 94    @Autowired
 95    private UserService userService;
 96    @Autowired
 97    private ReCaptchaUtility reCaptchaUtility;
 98    @Autowired
 99    @Qualifier("projectValidator")
100    private Validator projectValidator;
101
102    /**
103     * Register custom binders for Spring. Needed to run on app engine
104     * 
105     * @param binder
106     * @param request
107     */
108    @InitBinder
109    public void initBinder(WebDataBinder binder) {
110        binder.registerCustomEditor(Boolean.class, new CustomBooleanEditor(true));
111        binder.registerCustomEditor(String.class, new StringEditor(true));
112    }
113
114    /**
115     * Handles the request for search/list idea.
116     * 
117     * @param model Carries data for the view
118     * @return View name.
119     */
120    @RequestMapping(value = "/list", method = RequestMethod.GET)
121    public String listProjects() {
122        return "projects/list";
123    }
124
125    /**
126     * Creates project for the idea identified by ideaKey.
127     * 
128     * @param ideaKey for the {@link Idea}
129     * @param model Carries data for the view
130     * @return
131     */
132    @RequestMapping("/showForm/{ideaKey}")
133    public String edit(@PathVariable String ideaKey, Model model) {
134        ProjectDetail projectDetail = new ProjectDetail();
135        projectDetail.setProject(new Project());
136        ViewStatus viewStatus = new ViewStatus();
137        viewStatus.addData(WebConstants.PROJECT_DETAIL, projectDetail);
138        viewStatus.setStatus(SUCCESS);
139        Idea idea = ideaService.getIdeaByKey(ideaKey);
140        viewStatus.addData(WebConstants.IDEA_TITLE, idea.getTitle());
141        model.addAttribute(VIEW_STATUS, viewStatus);
142        model.addAttribute("ideaKey", ideaKey);
143        return "projects/edit";
144    }
145
146    /**
147     * Displays the project details identified by projectKey
148     * 
149     * @param projectKey the id of {@link Project} to display
150     * @param model Carries data for the view
151     * @param req reference of the {@link HttpServletRequest}
152     * @return
153     */
154
155    @RequestMapping("/show/{projectKey}")
156    public String show(@PathVariable String projectKey, Map<String, Object> model,
157                    HttpServletRequest req) {
158        ViewStatus viewStatus = new ViewStatus();
159        User user = null;
160        if (req.getSession(true).getAttribute(WebConstants.USER) != null)
161            user = (User) req.getSession(true).getAttribute(WebConstants.USER);
162
163        ProjectDetail projectDetail = projectBuilder.getProjectDetail(projectKey);
164        if (null != projectDetail && null != projectDetail.getProject()) {
165            Project project = projectDetail.getProject();
166            Idea associatedIdea = ideaService.getIdeaByKey(project.getIdeaKey());
167            /*
168             * Set containing the status for which the idea should not be
169             * displayed
170             */
171            Set<String> setOfStatus = new HashSet<String>();
172            setOfStatus.add(Idea.STATUS_DELETED);
173            setOfStatus.add(Idea.STATUS_OBJECTIONABLE);
174            /*
175             * If the idea has status contained in the set created above,set the
176             * idea key for the project to null
177             */
178            if (setOfStatus.contains(associatedIdea.getStatus())) {
179                project.setIdeaKey(null);
180
181                logger.debug("The idea is either deleted or objectionable," +
182                                "hence setting the idea key for project to null");
183            } else {
184                projectDetail.setIdeaTitle(associatedIdea.getTitle());
185            }
186            if (user != null)
187                logger.debug("Checking if project is editable to the user with userkey ="
188                                + user.getUserKey());
189            projectDetail.setProjectEditable(isProjectEditable(projectDetail, user));
190            logger.info("projectDetail.projectEditable is set to ="
191                            + projectDetail.isProjectEditable());
192            viewStatus.addData(WebConstants.PROJECT_DETAIL, projectDetail);
193            viewStatus.setStatus(SUCCESS);
194        } else {
195            viewStatus.setStatus(ERROR);
196            viewStatus.addMessage(ERROR, WebConstants.RECORD_NOT_FOUND);
197        }
198        model.put(VIEW_STATUS, viewStatus);
199        return "projects/show";
200    }
201
202    /**
203     * Check for project edit-able attribute on the basis of logged in user.
204     * 
205     * @param projectDetail {@link ProjectDetail} to edit
206     * @return boolean status of the action
207     */
208    private boolean isProjectEditable(ProjectDetail projectDetail, User user) {
209        boolean isEditable = false;
210        if (projectDetail.getProject() != null) {
211            if (user != null) {
212                if (projectDetail.getUser() != null) {
213                    if (user.getUserKey() != null
214                                    && user.getUserKey().equalsIgnoreCase(
215                                                    projectDetail.getUser().getUserKey())) {
216                        isEditable = true;
217                    }
218                }
219                for (Developer developer : projectDetail.getDevelopers()) {
220                    logger.debug("developer's status =" + developer.getStatus());
221                    if (user.getUserKey().equalsIgnoreCase(developer.getUserKey())) {
222                        isEditable = true;
223                        break;
224                    }
225                }
226            }
227
228        }
229        return isEditable;
230    }
231
232    /**
233     * Handles request for editing an project. Validates the Project details
234     * and saves the project if no validation errors are found.
235     * 
236     * @return name of project detail JSP to be shown.
237     */
238    @RequestMapping("/editProject/{projectKey}")
239    public String editProject(@PathVariable String projectKey,
240                    HttpSession session,
241                    Map<String, Object> model) {
242        User user = (User) session.getAttribute(WebConstants.USER);
243        ViewStatus viewStatus = new ViewStatus();
244        ProjectDetail projectDetail = projectBuilder.getProjectDetail(projectKey);
245        projectDetail.setProjectEditable(isProjectEditable(projectDetail, user));
246        if (null != projectDetail.getProject()) {
247            projectDetail.setIdeaTitle(ideaService.getIdeaByKey(
248                            projectDetail.getProject().getIdeaKey()).getTitle());
249            viewStatus.addData(WebConstants.PROJECT_DETAIL, projectDetail);
250            viewStatus.setStatus(SUCCESS);
251        } else {
252            viewStatus.setStatus(ERROR);
253            viewStatus.addMessage(ERROR, WebConstants.RECORD_NOT_FOUND);
254        }
255        Idea idea = ideaService.getIdeaByKey(projectDetail.getProject().getIdeaKey());
256        model.put(VIEW_STATUS, viewStatus);
257        viewStatus.addData(WebConstants.IDEA_TITLE, idea.getTitle());
258        model.put("ideaKey", projectDetail.getProject().getIdeaKey());
259        model.put("projectKey", projectDetail.getProject().getKey());
260        model.put("editProject", true);
261        return "projects/edit";
262    }
263
264    /**
265     * Handles request for creating an project. Validates the Project details
266     * and saves the project if no validation errors are found.
267     * 
268     * @return name of project detail JSP to be shown.
269     */
270    @RequestMapping(value = "/create", method = RequestMethod.POST)
271    public String createProject(HttpServletRequest request,
272                    @RequestParam(required = true) String ideaKey,
273                    @RequestParam(required = false) String projectKey,
274                    @RequestParam(required = false, value = "devName") String[] devNames,
275                    @RequestParam(required = false, value = "email") String[] emails,
276                    @RequestParam(required = false, value = "status") String[] statusArr,
277                    @RequestParam(required = false, value = "devKey") String[] devKeys,
278                    @RequestParam(required = false, value = "logoFile") MultipartFile logoFile,
279                    @ModelAttribute Project project,
280                    BindingResult errors,
281                    Map<String, Object> model,
282                    @RequestParam String recaptchaChallengeField,
283                    @RequestParam String recaptchaResponseField,
284                    HttpSession session) throws IOException {
285
286        ViewStatus viewStatus = new ViewStatus();
287        Boolean captchaValidation = reCaptchaUtility.verifyCaptcha(request.getRemoteAddr(),
288                        recaptchaChallengeField,
289                        recaptchaResponseField);
290        User user = (User) session.getAttribute(WebConstants.USER);
291        ProjectDetail projectDetail = new ProjectDetail();
292        /* create developer list. */
293        projectDetail.setDevelopers(createDeveloperList(devNames, emails, statusArr,
294                        devKeys, user));
295        projectDetail.setProject(project);
296        String ideaTitle = ideaService.getIdeaByKey(ideaKey).getTitle();
297        projectDetail.getProject().setIdeaKey(ideaKey);
298        if (projectKey != null) {
299            projectDetail.getProject().setKey(projectKey);
300        }
301        if (!captchaValidation) {
302            getViewStatusForInvalidCaptcha(model, viewStatus, projectDetail, ideaTitle, user);
303            return "projects/edit";
304        }
305        uploadLogo(projectKey, logoFile, projectDetail);
306        /* call projectValidator to validate projectDetail object */
307        projectValidator.validate(projectDetail, errors);
308        /* If the errors exist in the data being posted, return to edit page */
309        if (errors.hasErrors()) {
310            viewStatus = ViewStatus.createProjectErrorViewStatus(errors);
311            model.put(WebConstants.VIEW_STATUS, viewStatus);
312            return "projects/edit";
313        }
314        projectDetail = createProjectAndGetDetail(user, projectDetail, ideaTitle);
315        if (null != projectDetail.getProject()) {
316            viewStatus.addData(WebConstants.PROJECT_DETAIL, projectDetail);
317            viewStatus.setStatus(SUCCESS);
318        } else {
319            viewStatus.setStatus(ERROR);
320            viewStatus.addMessage(ERROR, WebConstants.RECORD_NOT_FOUND);
321        }
322        model.put("editProject", "");
323        model.put(VIEW_STATUS, viewStatus);
324        // redirect to project detail page
325        if (null != projectKey) {
326            return "redirect:show/" + projectKey;
327        } else if (null != projectDetail.getProject()) {
328            return "redirect:show/" + projectDetail.getProject().getKey();
329        } else {
330            return "projects/show";
331        }
332    }
333
334    /**
335     * Get View Status For Captcha Invalid
336     * 
337     * @param model Carries data for the view
338     * @param viewStatus
339     * @param projectDetail
340     * @param ideaTitle
341     */
342    private void getViewStatusForInvalidCaptcha(Map<String, Object> model, ViewStatus viewStatus,
343                    ProjectDetail projectDetail, String ideaTitle, User user) {
344        viewStatus.addMessage(WebConstants.ERROR, WebConstants.CAPTCHA_MISMATCH);
345        viewStatus.addData(WebConstants.IDEA_TITLE, ideaTitle);
346        model.put("ideaKey", projectDetail.getProject().getIdeaKey());
347        model.put("projectKey", projectDetail.getProject().getKey());
348        /*
349         * If project is not created then delete user information from developer
350         * list.
351         */
352        if (projectDetail.getProject().getKey() == null) {
353            Developer developerToDelete = null;
354            for (Developer developer : projectDetail.getDevelopers()) {
355                if (user.getDisplayName() != null && user.getEmailId() != null) {
356                    if (user.getDisplayName().equalsIgnoreCase(developer.getName())
357                                    && user.getEmailId().equalsIgnoreCase(developer.getEmailId())) {
358                        developerToDelete = developer;
359                        break;
360                    }
361                }
362            }
363            if (developerToDelete != null) {
364                projectDetail.getDevelopers().remove(developerToDelete);
365            }
366        } else {
367            model.put("editProject", true);
368        }
369        viewStatus.addData(WebConstants.PROJECT_DETAIL, projectDetail);
370        model.put(VIEW_STATUS, viewStatus);
371    }
372
373    /**
374     * Creates the project and retrieves the project details.
375     * 
376     * @param user creating the project.
377     * @param projectDetail
378     * @param ideaTitle
379     * @return
380     */
381    private ProjectDetail createProjectAndGetDetail(User user, ProjectDetail projectDetail,
382                    String ideaTitle) {
383        Project project = projectService.createOrUpdateProject(projectDetail.getProject(), user);
384        // handle developers functionality.
385        handleDeveloper(projectDetail.getDevelopers(), user, project);
386        projectDetail = projectBuilder.getProjectDetail(project.getKey());
387        projectDetail.setIdeaTitle(ideaTitle);
388        projectDetail.setProjectEditable(isProjectEditable(projectDetail, user));
389        return projectDetail;
390    }
391
392    /**
393     * @param projectKey
394     * @param logoFile
395     * @param projectDetail
396     * @throws IOException
397     */
398    private void uploadLogo(String projectKey, MultipartFile logoFile, ProjectDetail projectDetail)
399                    throws IOException {
400        if (logoFile != null && logoFile.getBytes().length > 0) {
401            try {
402                Blob file = new Blob(logoFile.getBytes());
403                projectDetail.getProject().setLogo(file);
404            } catch (IOException e) {
405                logger.error("couldn't find an Image at " + logoFile, e);
406            }
407        } else {
408            Project project1 = new Project();
409            if (projectService.getProjectById(projectKey) != null)
410                project1 = projectService.getProjectById(projectKey);
411            if (project1.getLogo() != null && project1.getLogo().getBytes().length > 0) {
412                Blob file = new Blob(project1.getLogo().getBytes());
413                projectDetail.getProject().setLogo(file);
414            }
415        }
416    }
417
418    /**
419     * create Developer List
420     * 
421     * @param devName
422     * @param email
423     * @param status
424     * @param devKey
425     * @param user
426     * @return List<Developer>
427     */
428    private List<Developer> createDeveloperList(String[] devName, String[] email, String[] status,
429                    String[] devKey, User user) {
430        List<Developer> developers = new ArrayList<Developer>();
431        Set<String> emailsSet = new HashSet<String>();
432
433        if ((devName != null && devName.length > 0) && (email != null && email.length > 0)) {
434            Developer developer = null;
435            for (int i = 0; i < devName.length; i++) {
436                if (validDeveloperData(devName, email, i)) {
437                    // Check if email ids are unique
438                    boolean unique = emailsSet.add(email[i]);
439                    if (unique) {
440                        developer = new Developer();
441                        developer.setEmailId(email[i]);
442                        developer.setName(devName[i]);
443                        // If devKey is not present, it is a create request
444                        if (devKey[i] != null && devKey[i].trim().length() > 0) {
445                            developer.setKey(devKey[i]);
446                        }
447                        // If status is not present, it is a create request
448                        if (status[i] != null && status[i].trim().length() > 0) {
449                            developer.setStatus(status[i]);
450                        }
451                        // While editing, set user key into developer object, if
452                        // developer's email id is same as users email id.
453                        if (developer.getEmailId().equals(user.getEmailId())) {
454                            // If user explicitly adding himself as a developer
455                            // while creating the project then set its user key
456                            // and status as accepted.
457                            developer.setUserKey(user.getUserKey());
458                            developer.setStatus(Developer.STATUS_REQUEST_ACCEPTED);
459                        }
460                        developers.add(developer);
461                    }
462                }
463            }
464        }
465        // Check if creator has not already added himself as developer.
466        boolean unique = emailsSet.add(user.getEmailId());
467        if (unique) {
468            Developer developer = new Developer();
469            developer.setEmailId(user.getEmailId());
470            developer.setName(user.getDisplayName());
471            developer.setUserKey(user.getUserKey());
472            developer.setStatus(Developer.STATUS_REQUEST_ACCEPTED);
473            logger.debug("Added project creator to it's developer list.");
474            developers.add(developer);
475        }
476        return developers;
477    }
478
479    /**
480     * check for valid Developer Data.
481     * 
482     * @param devName
483     * @param email
484     * @param index
485     * @return boolean
486     */
487    private boolean validDeveloperData(String[] devName, String[] email, int index) {
488        if (devName.length > index && email.length > index) {
489            String name = devName[index];
490            String emailId = email[index];
491            if ((name != null && name.trim().length() > 0 && !name.trim().equals(NAME))
492                            && (emailId != null && emailId.trim().length() > 0 && !emailId.trim()
493                            .equals(EMAILID))) {
494                return true;
495            }
496        }
497        return false;
498    }
499
500    /**
501     * This method check for new user and save them and send mail for joining
502     * the project.
503     * 
504     * @param developers list of developer
505     * @param user
506     * @param project
507     * @param isUpdateRequest
508     * @return List<Developer>
509     */
510    private List<Developer> handleDeveloper(List<Developer> developers, User user, Project project) {
511        List<Developer> updatedDevelopers = new ArrayList<Developer>();
512        List<String> emailList = new ArrayList<String>();
513        for (Developer developer : developers) {
514            logger.debug("Developer status =" + developer.getStatus() + " , user.userkey="
515                            + user.getUserKey() + " ,developer.userkey =" + developer.getUserKey());
516            if (developer.getStatus().equalsIgnoreCase(Developer.STATUS_JOIN_REQUEST)) {
517                developer.setStatus(Developer.STATUS_REQUEST_ALLREADY_SENT);
518                developer.setProjectKey(project.getKey());
519                developer = developerService.saveDeveloper(developer);
520                updatedDevelopers.add(developer);
521                emailList.add(developer.getEmailId() + SEMICOLON + developer.getName() + SEMICOLON
522                                + developer.getKey());
523            } else if (developer.getStatus().equalsIgnoreCase(Developer.STATUS_REQUEST_ACCEPTED)) {
524                developer.setProjectKey(project.getKey());
525                developer = developerService.saveDeveloper(developer);
526                updatedDevelopers.add(developer);
527            } else {
528                updatedDevelopers.add(developer);
529            }
530        }
531        // /* Send email to developer */
532        if (emailList.size() > 0) {
533            List<String> otherInfoList = new ArrayList<String>();
534            otherInfoList.add(user.getDisplayName());
535            otherInfoList.add(project.getName());
536            otherInfoList.add(project.getKey());
537            EmailManager.sendMail(PROJECT_EMAIL_TYPE_INVITE_TO_JOIN, emailList, otherInfoList);
538        }
539        return updatedDevelopers;
540    }
541
542    @RequestMapping("/joinProject/{projectKey}/{developerKey}/{emailId}")
543    public String joinProject(@PathVariable String projectKey, @PathVariable String developerKey,
544                    @PathVariable String emailId,
545                    Map<String, Object> model, HttpServletRequest req) {
546        User user = null;
547        ProjectDetail projectDetail = projectBuilder.getProjectDetail(projectKey);
548        Developer developer = developerService.getDeveloperById(developerKey);
549        if (projectDetail == null || projectDetail.getProject() == null || developer == null) {
550            return "error/data-access-error";
551        }
552        if (req.getSession(true).getAttribute(WebConstants.USER) != null) {
553            user = (User) req.getSession(true).getAttribute(WebConstants.USER);
554            if (null == user.getUserKey()) {
555                user = userService.addOrUpdateUser(user);
556                req.getSession(true).setAttribute(WebConstants.USER, user);
557            }
558        }
559
560        if (user != null) {
561            developer.setStatus(Developer.STATUS_REQUEST_ACCEPTED);
562            developer.setUserKey(user.getUserKey());
563            developerService.saveDeveloper(developer);
564            ViewStatus viewStatus = new ViewStatus();
565            viewStatus.addData(WebConstants.PROJECT_DETAIL, projectDetail);
566            viewStatus.setStatus(WebConstants.SUCCESS);
567            model.put(VIEW_STATUS, viewStatus);
568            // return "projects/show";
569        }
570        return "users/activate";
571    }
572
573    /**
574     * Handles the request for search/list Project.
575     * 
576     * @param model Carries data for the view
577     * @return View name.
578     */
579    // @RequestMapping(value = "/list", method = RequestMethod.GET)
580    // public String listProjects(Map<String, Object> model) {
581    @RequestMapping(value = "/get", method = RequestMethod.GET)
582    public String listProjects(@ModelAttribute RetrievalInfo retrievalInfo,
583                    Map<String, Object> model) {
584        /* Fetch the range parameters as sent in the request */
585        long startIndex = retrievalInfo.getStartIndex();
586        long noOfRecordsRequested = retrievalInfo.getNoOfRecords();
587        /* Get the idea list */
588        // List<Project> projects = new ArrayList<Project>();
589        List<Project> projects = projectService.listProjects(retrievalInfo);
590        Iterator<Project> iterator = projects.iterator();
591        Project projectWithDesc = null;
592        while (iterator.hasNext()) {
593            projectWithDesc = iterator.next();
594            projectWithDesc.setDescriptionAsString(projectWithDesc.getDescription());
595            shortenFields(projectWithDesc);
596        }
597        /* Map of data to be inserted into the view status object */
598        HashMap<String, Object> parameters = new HashMap<String, Object>();
599        /* Map containing the previous and next index values */
600        HashMap<String, Long> pagingMap = new HashMap<String, Long>();
601        /*
602         * If the size of the list is greater than the no. of records requested
603         * ,set the parameter 'next' to be used as start index for the next
604         * page retrieval.
605         */
606        if (projects != null && projects.size() > noOfRecordsRequested) {
607            pagingMap.put(WebConstants.NEXT, startIndex + noOfRecordsRequested);
608        } else {
609            /*
610             * If the list size is not greater than the number requested set
611             * the 'next' parameter to minus one
612             */
613            pagingMap.put(WebConstants.NEXT, (long) WebConstants.MINUS_ONE);
614        }
615        /*
616         * Set the parameter 'previous' to be used as the start index for the
617         * previous page retrieval
618         */
619        pagingMap.put(WebConstants.PREVIOUS, startIndex - noOfRecordsRequested);
620        /* Add the map containing the paging values to the map of parameters */
621        parameters.put(WebConstants.PAGING, pagingMap);
622        // Create viewStatus
623        ViewStatus viewStatus = createTheViewStatus(projects, parameters);
624        model.put(VIEW_STATUS, viewStatus);
625        return "projects/list";
626    }
627
628    /**
629     * Shortens the length of title and description fields
630     * 
631     * @param project
632     */
633    private void shortenFields(Project project) {
634        if (null != project) {
635            /* 50 chars for title */
636            project.setName(StringUtils.abbreviate(project.getName(), 50));
637            /* 150 chars for description */
638            project.setDescriptionAsString(StringUtils.abbreviate(project.getDescriptionAsString(),
639                            150));
640        }
641    }
642
643    /**
644     * Create the {@link ViewStatus} object containing the data retrieved.This
645     * object has the status codes set to success/error based on whether the
646     * parameter list contains data or not.
647     * 
648     * @param listOfProjects the list containing data
649     * @param hitCount
650     * @return object containing the data and status codes
651     */
652    private ViewStatus createTheViewStatus(List<?> listProjects, Map<String, ?> parameters) {
653        ViewStatus viewStatus = new ViewStatus();
654        /*
655         * If the list of ideas is not null and at least one idea
656         * exists create the view status object with status as 'success' and
657         * also set the data.
658         */
659        if (listProjects != null && listProjects.size() > WebConstants.ZERO) {
660            viewStatus.setStatus(SUCCESS);
661            viewStatus.addData(WebConstants.PROJECTS, listProjects);
662            viewStatus.addData(WebConstants.MY_IDEAS_COUNT, listProjects.size());
663            if (parameters != null) {
664                Iterator<String> keysIter = parameters.keySet().iterator();
665                String objectKey = null;
666                while (keysIter.hasNext()) {
667                    objectKey = keysIter.next();
668                    viewStatus.addData(objectKey, parameters.get(objectKey));
669                }
670            }
671        } else {/* In case the idea list is null or empty */
672            viewStatus.setStatus(WebConstants.ERROR);
673            viewStatus.addMessage(WebConstants.PROJECTS, WebConstants.NO_RECORDS_FOUND);
674        }
675        return viewStatus;
676    }
677
678    /**
679     * @param projectService the projectService to set
680     */
681    public void setProjectService(ProjectService projectService) {
682        this.projectService = projectService;
683    }
684
685    /**
686     * 
687     * @return the projectService
688     */
689    public ProjectService getProjectService() {
690        return projectService;
691    }
692
693}
694