001/* 002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Nicolas Chapurlat <nchapurlat@nuxeo.com> 018 */ 019 020package org.nuxeo.ecm.core.api.validation; 021 022import java.util.ArrayList; 023import java.util.List; 024 025import org.apache.commons.lang3.StringUtils; 026import org.apache.http.HttpStatus; 027import org.nuxeo.ecm.core.api.NuxeoException; 028 029/** 030 * Exception thrown when some process failed due to {@link ValidationViolation}. 031 * 032 * @since 7.1 033 */ 034public class DocumentValidationException extends NuxeoException { 035 036 protected static final String MESSAGE_SINGLE = "Constraint violation thrown%s: '%s'"; 037 038 protected static final String MESSAGE = "%s constraint violation(s) thrown. First one thrown%s: '%s', call " 039 + DocumentValidationException.class.getSimpleName() + ".getViolations() to get the others"; 040 041 private static final long serialVersionUID = 1L; 042 043 private DocumentValidationReport report; 044 045 public DocumentValidationException(DocumentValidationReport report) { 046 super(HttpStatus.SC_UNPROCESSABLE_ENTITY); 047 this.report = report; 048 } 049 050 public DocumentValidationException(String message) { 051 super(message, HttpStatus.SC_UNPROCESSABLE_ENTITY); 052 List<ValidationViolation> violations = new ArrayList<>(); 053 violations.add(new GlobalViolation(message)); 054 this.report = new DocumentValidationReport(violations); 055 } 056 057 public DocumentValidationReport getReport() { 058 return report; 059 } 060 061 @Override 062 public String getMessage() { 063 if (report.hasError()) { 064 int num = report.numberOfErrors(); 065 ValidationViolation violation = report.asList().get(0); 066 String xpath = ""; 067 if (violation instanceof ConstraintViolation) { 068 ConstraintViolation cv = (ConstraintViolation) violation; 069 xpath = cv.getPathAsString(); 070 } 071 var propertyMessage = StringUtils.isBlank(xpath) ? "" : String.format(" on property %s", xpath); 072 String violationMessage = violation.getMessage(null); 073 if (num > 1) { 074 return String.format(MESSAGE, report.numberOfErrors(), propertyMessage, violationMessage); 075 } else { 076 return String.format(MESSAGE_SINGLE, propertyMessage, violationMessage); 077 } 078 } else { 079 return super.getMessage(); 080 } 081 } 082 083}