001/*
002 * Copyright (c) 2006-2013 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     vpasquier
011 *     slacoin
012 */
013package org.nuxeo.ecm.automation;
014
015import java.util.LinkedList;
016import java.util.List;
017
018/**
019 * @since 5.7.2 Operation composite exception builder throwing @{link OperationCompoundException}.
020 */
021public class OperationCompoundExceptionBuilder {
022
023    protected final List<OperationException> accumulated = new LinkedList<OperationException>();
024
025    protected OperationException newThrowable(List<OperationException> causes) {
026        return new OperationCompoundException(getMessages(causes),
027                causes.toArray(new OperationException[causes.size()]));
028    }
029
030    protected String getMessages(List<OperationException> causes) {
031        StringBuilder stringBuilder = new StringBuilder();
032        for (OperationException operationException : causes) {
033            stringBuilder.append(operationException.getMessage());
034            stringBuilder.append(System.getProperty("line.separator"));
035        }
036        return stringBuilder.toString();
037    }
038
039    public void add(OperationException error) {
040        accumulated.add(error);
041    }
042
043    public void throwOnError() throws OperationException {
044        if (accumulated.isEmpty()) {
045            return;
046        }
047        throw newThrowable(accumulated);
048    }
049
050}