001/* Copyright (C) 2014 konik.io
002 *
003 * This file is part of the Konik library.
004 *
005 * The Konik library is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * The Konik library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with the Konik library. If not, see <http://www.gnu.org/licenses/>.
017 */
018package io.konik.validation;
019
020import io.konik.validator.annotation.Comfort;
021import io.konik.validator.annotation.Extended;
022import io.konik.zugferd.Invoice;
023import io.konik.zugferd.profile.ConformanceLevel;
024
025import java.util.Set;
026
027import javax.inject.Inject;
028import javax.inject.Named;
029import javax.inject.Singleton;
030import javax.validation.ConstraintViolation;
031import javax.validation.Validator;
032import javax.validation.groups.Default;
033
034/**
035 * Validates the invoice against the declared invoice profile.
036 */
037@Named
038@Singleton
039public class InvoiceValidator {
040
041   private Validator validator;
042
043   /**
044    * Instantiates a new invoice validator.
045    *
046    * @param validator the validator
047    */
048   @Inject
049   public InvoiceValidator(Validator validator) {
050      super();
051      this.validator = validator;
052   }
053
054   /**
055    * Validate the invoice
056    *
057    * @param invoice the invoice
058    * @return the sets the
059    */
060   public Set<ConstraintViolation<Invoice>> validate(Invoice invoice) {
061      ConformanceLevel conformanceLevel = invoice.getContext().getGuideline().getConformanceLevel();
062      Class<?>[] validationGroups = resolveIntoValidationGroups(conformanceLevel);
063      return validator.validate(invoice, validationGroups);
064   }
065
066   /**
067    * Resolve the given profile into bean validation groups.
068    *
069    * @param conformanceLevel the given profile
070    * @return the class[] list of validation group classes
071    */
072   public static Class<?>[] resolveIntoValidationGroups(ConformanceLevel conformanceLevel) {
073      switch (conformanceLevel) {
074      case BASIC:
075         return new Class[] { Default.class };
076      case COMFORT:
077         return new Class[] { Default.class, Comfort.class };
078      case EXTENDED:
079         return new Class[] { Default.class, Comfort.class, Extended.class };
080      default:
081         throw new IllegalArgumentException("Provided Profile:" + conformanceLevel + "not covered");
082      }
083   }
084}