com.seajas.search.attender.controller.ProfileController.java Source code

Java tutorial

Introduction

Here is the source code for com.seajas.search.attender.controller.ProfileController.java

Source

/**
 * Copyright (C) 2013 Seajas, the Netherlands.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.seajas.search.attender.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;

import com.seajas.search.attender.model.command.ProfileCommand;
import com.seajas.search.attender.model.profile.Profile;
import com.seajas.search.attender.model.profile.ProfileSubscriber;
import com.seajas.search.attender.model.profile.ProfileSubscriber.NotificationType;
import com.seajas.search.attender.service.attender.AttenderService;
import com.seajas.search.utilities.spring.security.model.User;

/**
 * Profile controller.
 * 
 * @author Jasper van Veghel <jasper@seajas.com>
 */
@RequestMapping("/profiles.html")
@Controller
public class ProfileController {
    /**
     * The logger.
     */
    private static final Logger logger = LoggerFactory.getLogger(ProfileController.class);

    /**
     * Attender service.
     */
    @Autowired
    private AttenderService attenderService;

    /**
     * The validator.
     */
    @Qualifier("profileValidator")
    @Autowired
    private Validator validator;

    /**
     * User attribute.
     * 
     * @return User
     */
    @ModelAttribute("user")
    public User populateUser() {
        return attenderService.getUser();
    }

    /**
     * Data attribute.
     * 
     * @return List<Profile>
     */
    @ModelAttribute("data")
    public List<Profile> populateData() {
        return attenderService.getProfiles();
    }

    /**
     * Available languages attribute.
     * 
     * @return List<String>
     */
    @ModelAttribute("availableLanguages")
    public List<String> populateAvailableLanguages() {
        return attenderService.getAvailableSearchLanguages();
    }

    /**
     * Available time zones attribute.
     * 
     * @return List<String>
     */
    @ModelAttribute("availableTimeZones")
    public List<String> populateAvailableTimeZones() {
        List<String> result = new ArrayList<String>();

        for (String timeZone : TimeZone.getAvailableIDs())
            if (timeZone.contains("/") && !timeZone.startsWith("Etc/"))
                result.add(timeZone);

        // Also incorporate any custom timezones (typically from attender requests)

        for (Profile profile : attenderService.getProfiles())
            for (ProfileSubscriber subscriber : profile.getSubscribers())
                if (!result.contains(subscriber.getTimeZone()))
                    result.add(subscriber.getTimeZone());

        Collections.sort(result);

        result.add(0, "UTC");

        return result;
    }

    /**
     * Handle the request.
     * 
     * @param model
     * @return String
     * @throws Exception
     */
    @RequestMapping(method = RequestMethod.GET)
    public String handleRequest(final ModelMap model) throws Exception {
        model.put("profileCommand", new ProfileCommand());

        return "profiles";
    }

    /**
     * Render the submit action in the same way as a regular page view is rendered.
     * 
     * @param command
     * @param result
     * @param model
     * @param request
     * @return String
     * @throws Exception
     */
    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("profileCommand") final ProfileCommand command,
            final BindingResult result, final ModelMap model, final WebRequest request) throws Exception {
        // Collect and set the subscribers by the individual values

        List<String> subscriberEmails = new ArrayList<String>();
        List<String> subscriberEmailLanguages = new ArrayList<String>();
        List<String> subscriberTimeZones = new ArrayList<String>();
        List<String> subscriberTypes = new ArrayList<String>();
        List<String> subscriberDays = new ArrayList<String>();
        List<String> subscriberHours = new ArrayList<String>();
        List<String> subscriberMinutes = new ArrayList<String>();
        List<String> subscriberIntervals = new ArrayList<String>();
        List<String> subscriberMaximums = new ArrayList<String>();
        List<String> subscriberUniqueIds = new ArrayList<String>();
        List<String> subscriberConfirmations = new ArrayList<String>();
        List<String> subscriberLastNotifications = new ArrayList<String>();

        if (request.getParameterValues("subscriberEmails") != null)
            for (String subscriberEmail : request.getParameterValues("subscriberEmails"))
                subscriberEmails.add(subscriberEmail);

        command.setSubscriberEmails(subscriberEmails);

        if (request.getParameterValues("subscriberEmailLanguages") != null)
            for (String subscriberEmailLanguage : request.getParameterValues("subscriberEmailLanguages"))
                subscriberEmailLanguages.add(subscriberEmailLanguage);

        command.setSubscriberEmailLanguages(subscriberEmailLanguages);

        if (request.getParameterValues("subscriberTimeZones") != null)
            for (String subscriberTimeZone : request.getParameterValues("subscriberTimeZones"))
                subscriberTimeZones.add(subscriberTimeZone);

        command.setSubscriberTimeZones(subscriberTimeZones);

        if (request.getParameterValues("subscriberNotificationTypes") != null)
            for (String subscriberType : request.getParameterValues("subscriberNotificationTypes"))
                subscriberTypes.add(subscriberType);

        command.setSubscriberTypes(subscriberTypes);

        if (request.getParameterValues("subscriberNotificationDays") != null)
            for (String subscriberDay : request.getParameterValues("subscriberNotificationDays"))
                subscriberDays.add(subscriberDay);

        command.setSubscriberDays(subscriberDays);

        if (request.getParameterValues("subscriberNotificationHours") != null)
            for (String subscriberHour : request.getParameterValues("subscriberNotificationHours"))
                subscriberHours.add(subscriberHour);

        command.setSubscriberHours(subscriberHours);

        if (request.getParameterValues("subscriberNotificationMinutes") != null)
            for (String subscriberMinute : request.getParameterValues("subscriberNotificationMinutes"))
                subscriberMinutes.add(subscriberMinute);

        command.setSubscriberMinutes(subscriberMinutes);

        if (request.getParameterValues("subscriberNotificationIntervals") != null)
            for (String subscriberInterval : request.getParameterValues("subscriberNotificationIntervals"))
                subscriberIntervals.add(StringUtils.isEmpty(subscriberInterval) ? "-1" : subscriberInterval);

        command.setSubscriberIntervals(subscriberIntervals);

        if (request.getParameterValues("subscriberNotificationMaximums") != null)
            for (String subscriberMaximum : request.getParameterValues("subscriberNotificationMaximums"))
                subscriberMaximums.add(StringUtils.isEmpty(subscriberMaximum) ? "-1" : subscriberMaximum);

        command.setSubscriberMaximums(subscriberMaximums);

        if (request.getParameterValues("subscriberNotificationUniqueIds") != null)
            for (String subscriberUniqueId : request.getParameterValues("subscriberNotificationUniqueIds"))
                subscriberUniqueIds.add(subscriberUniqueId);

        command.setSubscriberUniqueIds(subscriberUniqueIds);

        if (request.getParameterValues("subscriberNotificationConfirmations") != null)
            for (String subscriberConfirmation : request.getParameterValues("subscriberNotificationConfirmations"))
                subscriberConfirmations.add(subscriberConfirmation);

        command.setSubscriberConfirmations(subscriberConfirmations);

        if (request.getParameterValues("subscriberNotificationLastNotifications") != null)
            for (String subscriberLastNotification : request
                    .getParameterValues("subscriberNotificationLastNotifications"))
                subscriberLastNotifications.add(subscriberLastNotification);

        command.setSubscriberLastNotifications(subscriberLastNotifications);

        // Collect and set the parameters

        if (request.getParameterValues("searchParameterFormat") != null)
            command.setSearchParameterFormat(request.getParameterValues("searchParameterFormat")[0]);
        if (request.getParameterValues("searchParameterLanguage") != null)
            command.setSearchParameterLanguage(request.getParameterValues("searchParameterLanguage")[0]);
        if (request.getParameterValues("searchParameterAuthor") != null
                && !StringUtils.isEmpty(request.getParameterValues("searchParameterLanguage")[0]))
            command.setSearchParameterAuthor(request.getParameterValues("searchParameterAuthor")[0]);
        if (request.getParameterValues("searchParameterType") != null
                && !StringUtils.isEmpty(request.getParameterValues("searchParameterType")[0]))
            command.setSearchParameterType(request.getParameterValues("searchParameterType")[0]);
        if (request.getParameterValues("searchParameterGeo") != null
                && !StringUtils.isEmpty(request.getParameterValues("searchParameterGeo")[0]))
            command.setSearchParameterGeo(request.getParameterValues("searchParameterGeo")[0]);

        // Collect and set the taxonomy identifiers

        List<String> taxonomyIdentifiersCommand = new ArrayList<String>();

        if (request.getParameterValues("taxonomyIdentifiersList") != null)
            for (String taxonomyIdentifier : request.getParameterValues("taxonomyIdentifiersList")[0].trim()
                    .split(" "))
                if (!StringUtils.isBlank(taxonomyIdentifier))
                    taxonomyIdentifiersCommand.add(taxonomyIdentifier.trim());

        command.setTaxonomyIdentifiers(taxonomyIdentifiersCommand);

        // Update the enabled attribute

        if (request.getParameter("isEnabled") == null)
            command.setIsEnabled(false);

        validator.validate(command, result);

        if (!result.hasErrors()) {
            // Any search parameter validation errors should have been caught by the validator

            Map<String, String> searchParameters = new HashMap<String, String>();

            if (!StringUtils.isEmpty(command.getSearchParameterFormat()))
                searchParameters.put("dcterms_format", command.getSearchParameterFormat());
            if (!StringUtils.isEmpty(command.getSearchParameterLanguage()))
                searchParameters.put("dcterms_language", command.getSearchParameterLanguage());
            if (!StringUtils.isEmpty(command.getSearchParameterAuthor()))
                searchParameters.put("dcterms_author", command.getSearchParameterAuthor());
            if (!StringUtils.isEmpty(command.getSearchParameterType()))
                searchParameters.put("dcterms_type", command.getSearchParameterType());
            if (!StringUtils.isEmpty(command.getSearchParameterGeo()))
                searchParameters.put("geo_total", command.getSearchParameterGeo());

            // Any number formatting exceptions should have been caught by the validator

            List<Integer> taxonomyIdentifiers = new ArrayList<Integer>();

            for (String taxonomyIdentifier : command.getTaxonomyIdentifiers()) {
                Integer identifier = Integer.parseInt(taxonomyIdentifier);

                logger.info("Profile will be narrowed down by taxonomy identifiers - adding " + identifier);

                taxonomyIdentifiers.add(identifier);
            }

            // Any length inconsistencies should have been intercepted by the validator

            List<ProfileSubscriber> subscribers = new ArrayList<ProfileSubscriber>();

            if (!command.getAction().equals("delete"))
                for (int i = 0; i < subscriberEmails.size(); i++)
                    if (!StringUtils.isEmpty(subscriberEmails.get(i))) {
                        Long subscriberLastNotification = null;
                        String uniqueId = null;

                        if (!StringUtils.isEmpty(subscriberLastNotifications.get(i)))
                            try {
                                subscriberLastNotification = Long.valueOf(subscriberLastNotifications.get(i));
                            } catch (NumberFormatException e) {
                                // Do nothing, if it's simply incorrect
                            }
                        if (!StringUtils.isEmpty(subscriberUniqueIds.get(i))
                                && subscriberUniqueIds.get(i).length() > 10)
                            uniqueId = subscriberUniqueIds.get(i);

                        subscribers.add(new ProfileSubscriber(subscriberEmails.get(i),
                                subscriberEmailLanguages.get(i), Boolean.valueOf(subscriberConfirmations.get(i)),
                                uniqueId, subscriberTimeZones.get(i),
                                NotificationType.valueOf(subscriberTypes.get(i)),
                                Integer.valueOf(subscriberDays.get(i)), Integer.valueOf(subscriberHours.get(i)),
                                Integer.valueOf(subscriberMinutes.get(i)),
                                Integer.valueOf(subscriberIntervals.get(i)),
                                Integer.valueOf(subscriberMaximums.get(i)),
                                subscriberLastNotification != null && subscriberLastNotification > 0
                                        ? new Date(subscriberLastNotification)
                                        : null));
                    }

            if (command.getAction().equals("add"))
                attenderService.addProfile(command.getQuery(), command.getIsEnabled(), subscribers,
                        searchParameters, taxonomyIdentifiers);
            else if (command.getAction().equals("edit"))
                attenderService.modifyProfile(command.getId(), command.getQuery(), command.getIsEnabled(),
                        subscribers, searchParameters, taxonomyIdentifiers);
            else if (command.getAction().equals("delete"))
                attenderService.deleteProfile(command.getId());

            // Re-populate the data

            model.put("data", populateData());

            command.clear();
        }

        return "profiles";
    }
}