com.seajas.search.attender.validator.ProfileValidator.java Source code

Java tutorial

Introduction

Here is the source code for com.seajas.search.attender.validator.ProfileValidator.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.validator;

import java.util.Arrays;
import java.util.List;
import java.util.TimeZone;
import java.util.Vector;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.seajas.search.attender.model.command.ProfileCommand;
import com.seajas.search.attender.model.profile.ProfileSubscriber.NotificationType;
import com.seajas.search.attender.service.attender.AttenderService;

/**
 * Profile validator.
 * 
 * @author Jasper van Veghel <jasper@seajas.com>
 */
@Component("profileValidator")
public class ProfileValidator implements Validator {
    /**
     * The attender service.
     */
    @Autowired
    private AttenderService attenderService;

    /**
     * Determine whether this validator supports the command object.
     * 
     * @param klass
     * @return boolean
     */
    @Override
    @SuppressWarnings("rawtypes")
    public boolean supports(final Class klass) {
        return klass.equals(ProfileCommand.class);
    }

    /**
     * Validate the given command object.
     * 
     * @param command
     * @param errors
     */
    @Override
    public void validate(final Object command, final Errors errors) {
        ProfileCommand profile = (ProfileCommand) command;

        if (profile.getAction().equals("add") || profile.getAction().equals("edit")) {
            if (StringUtils.isEmpty(profile.getQuery()))
                errors.rejectValue("query", "profiles.error.query.empty");

            // Validate the subscribers

            int numberOfSubscribers = profile.getSubscriberEmails().size();

            if (numberOfSubscribers == 0)
                errors.rejectValue("subscriberEmails", "profiles.error.subscriber.emails.empty");
            else if (profile.getSubscriberEmailLanguages().size() != numberOfSubscribers)
                errors.rejectValue("subscriberEmailLanguages", "profiles.error.subscriber.email.languages.empty");
            else if (profile.getSubscriberTimeZones().size() != numberOfSubscribers)
                errors.rejectValue("subscriberTimeZones", "profiles.error.subscriber.timezones.empty");
            else if (profile.getSubscriberTypes().size() != numberOfSubscribers)
                errors.rejectValue("subscriberTypes", "profiles.error.subscriber.types.empty");
            else if (profile.getSubscriberDays().size() != numberOfSubscribers)
                errors.rejectValue("subscriberDays", "profiles.error.subscriber.days.empty");
            else if (profile.getSubscriberHours().size() != numberOfSubscribers)
                errors.rejectValue("subscriberHours", "profiles.error.subscriber.hours.empty");
            else if (profile.getSubscriberMinutes().size() != numberOfSubscribers)
                errors.rejectValue("subscriberMinutes", "profiles.error.subscriber.minutes.empty");
            else if (profile.getSubscriberIntervals().size() != numberOfSubscribers)
                errors.rejectValue("subscriberIntervals", "profiles.error.subscriber.intervals.empty");
            else if (profile.getSubscriberMaximums().size() != numberOfSubscribers)
                errors.rejectValue("subscriberMaximums", "profiles.error.subscriber.maximums.empty");
            else {
                List<String> emails = new Vector<String>(), types = new Vector<String>();

                for (int i = 0; i < profile.getSubscriberEmails().size(); i++) {
                    // Validate the e-mail

                    String subscriberEmail = profile.getSubscriberEmails().get(i);

                    // Skip if empty

                    if (StringUtils.isEmpty(subscriberEmail))
                        continue;

                    if (!EmailValidator.getInstance().isValid(subscriberEmail)) {
                        errors.rejectValue("subscriberEmails", "profiles.error.subscriber.emails.invalid");

                        break;
                    }

                    String subscriberEmailLanguage = profile.getSubscriberEmailLanguages().get(i);

                    if (StringUtils.isEmpty(subscriberEmailLanguage)) {
                        errors.rejectValue("subscriberEmailLanguages",
                                "profiles.error.subscriber.email.languages.invalid");

                        break;
                    } else if (!attenderService.getAvailableSearchLanguages().contains(subscriberEmailLanguage)) {
                        errors.rejectValue("subscriberEmailLanguages",
                                "profiles.error.subscriber.email.languages.invalid");

                        break;
                    }

                    String subscriberTimeZone = profile.getSubscriberTimeZones().get(i);

                    if (StringUtils.isEmpty(subscriberTimeZone)) {
                        errors.rejectValue("subscriberTimeZones", "profiles.error.subscriber.timezones.invalid");

                        break;
                    } else if (!Arrays.asList(TimeZone.getAvailableIDs()).contains(subscriberTimeZone)
                            && !subscriberTimeZone.matches("^GMT[+\\-][0-9]{2}:[0-9]{2}$")) {
                        errors.rejectValue("subscriberTimeZones", "profiles.error.subscriber.timezones.invalid");

                        break;
                    }

                    String subscriberType = profile.getSubscriberTypes().get(i);

                    if (StringUtils.isEmpty(subscriberType)) {
                        errors.rejectValue("subscriberTypes", "profiles.error.subscriber.types.invalid");

                        break;
                    }

                    try {
                        NotificationType.valueOf(subscriberType);
                    } catch (IllegalArgumentException e) {
                        errors.rejectValue("subscriberTypes", "profiles.error.subscriber.types.invalid");

                        break;
                    }

                    String subscriberDay = profile.getSubscriberDays().get(i);

                    if (StringUtils.isEmpty(subscriberDay)) {
                        errors.rejectValue("subscriberDays", "profiles.error.subscriber.days.invalid");

                        break;
                    }

                    try {
                        Integer dayNumber = Integer.parseInt(subscriberDay);

                        if (dayNumber < 0 || dayNumber > 6) {
                            errors.rejectValue("subscriberDays", "profiles.error.subscriber.days.invalid");

                            break;
                        }
                    } catch (NumberFormatException e) {
                        errors.rejectValue("subscriberDays", "profiles.error.subscriber.days.invalid");

                        break;
                    }

                    String subscriberHour = profile.getSubscriberHours().get(i);

                    if (StringUtils.isEmpty(subscriberHour)) {
                        errors.rejectValue("subscriberHours", "profiles.error.subscriber.hours.invalid");

                        break;
                    }

                    try {
                        Integer hourNumber = Integer.parseInt(subscriberHour);

                        if (hourNumber < 0 || hourNumber > 23) {
                            errors.rejectValue("subscriberHours", "profiles.error.subscriber.hours.invalid");

                            break;
                        }
                    } catch (NumberFormatException e) {
                        errors.rejectValue("subscriberHours", "profiles.error.subscriber.hours.invalid");

                        break;
                    }

                    String subscriberMinute = profile.getSubscriberMinutes().get(i);

                    if (StringUtils.isEmpty(subscriberMinute)) {
                        errors.rejectValue("subscriberMinutes", "profiles.error.subscriber.minutes.invalid");

                        break;
                    }

                    try {
                        Integer minuteNumber = Integer.parseInt(subscriberMinute);

                        if (minuteNumber < 0 || minuteNumber > 59) {
                            errors.rejectValue("subscriberMinutes", "profiles.error.subscriber.minutes.invalid");

                            break;
                        }
                    } catch (NumberFormatException e) {
                        errors.rejectValue("subscriberMinutes", "profiles.error.subscriber.minutes.invalid");

                        break;
                    }

                    String subscriberInterval = profile.getSubscriberIntervals().get(i);

                    if (StringUtils.isEmpty(subscriberInterval)) {
                        errors.rejectValue("subscriberIntervals", "profiles.error.subscriber.intervals.invalid");

                        break;
                    }

                    try {
                        Integer intervalNumber = Integer.parseInt(subscriberInterval);

                        // XXX: An arbitrary, but not outrageously high number

                        if (intervalNumber < -1 || intervalNumber > 60000) {
                            errors.rejectValue("subscriberIntervals",
                                    "profiles.error.subscriber.intervals.invalid");

                            break;
                        }
                    } catch (NumberFormatException e) {
                        errors.rejectValue("subscriberIntervals", "profiles.error.subscriber.intervals.invalid");

                        break;
                    }

                    String subscriberMaximum = profile.getSubscriberMaximums().get(i);

                    if (StringUtils.isEmpty(subscriberMaximum)) {
                        errors.rejectValue("subscriberMaximums", "profiles.error.subscriber.maximums.invalid");

                        break;
                    }

                    try {
                        Integer maximumNumber = Integer.parseInt(subscriberMaximum);

                        // XXX: An arbitrary, but not outrageously high number

                        if (maximumNumber < -1 || maximumNumber > 60000) {
                            errors.rejectValue("subscriberMaximums", "profiles.error.subscriber.maximums.invalid");

                            break;
                        }
                    } catch (NumberFormatException e) {
                        errors.rejectValue("subscriberMaximums", "profiles.error.subscriber.maximums.invalid");

                        break;
                    }

                    if (subscriberMaximum.equals("-1") && !subscriberInterval.equals("-1"))
                        errors.rejectValue("subscriberMaximums", "profiles.error.subscriber.maximums.invalid");
                    if (subscriberInterval.equals("-1") && !subscriberMaximum.equals("-1"))
                        errors.rejectValue("subscriberIntervals", "profiles.error.subscriber.intervals.invalid");

                    emails.add(subscriberEmail);
                    types.add(subscriberType);
                }

                if (emails.size() == 0)
                    errors.rejectValue("subscriberEmails", "profiles.error.subscriber.emails.empty");
                else {
                    // Now check for duplicates

                    for (int i = 0; i < emails.size(); i++) {
                        int occurs = 0;

                        for (int j = 0; j < emails.size(); j++) {
                            String duplicateEmail = emails.get(j), duplicateType = types.get(j);

                            if (duplicateEmail.equals(emails.get(i)) && duplicateType.equals(types.get(i)))
                                occurs++;
                        }

                        if (occurs > 1) {
                            errors.rejectValue("subscriberEmails", "profiles.error.subscriber.emails.duplicate");

                            break;
                        }
                    }
                }
            }

            // Validate the search parameters

            if (!StringUtils.isEmpty(profile.getSearchParameterFormat()))
                try {
                    MediaType.parseMediaTypes(profile.getSearchParameterFormat().replaceAll(" ", ","));
                } catch (IllegalArgumentException e) {
                    errors.rejectValue("searchParameterFormat", "profiles.error.search.parameter.format.invalid");
                }
            else if (!StringUtils.isEmpty(profile.getSearchParameterLanguage())) {
                if (!attenderService.getAvailableSearchLanguages().contains(profile.getSearchParameterLanguage()))
                    errors.rejectValue("searchParameterLanguage",
                            "profiles.error.search.parameter.language.invalid");
            }

            // Validate the taxonomy identifiers

            for (String taxonomyIdentifier : profile.getTaxonomyIdentifiers())
                try {
                    if (StringUtils.isEmpty(taxonomyIdentifier))
                        errors.rejectValue("taxonomyIdentifiers", "profiles.error.taxonomy.identifiers.empty");

                    Integer.parseInt(taxonomyIdentifier);
                } catch (NumberFormatException e) {
                    errors.rejectValue("taxonomyIdentifiers", "profiles.error.taxonomy.identifiers.invalid");

                    break;
                }
        }
    }
}