001/*
002 * (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Julien Carsique
016 *
017 */
018
019package org.nuxeo.connect.update.task.standalone.commands;
020
021import java.util.ArrayList;
022import java.util.List;
023import java.util.Map;
024
025import org.nuxeo.connect.update.PackageException;
026import org.nuxeo.connect.update.ValidationStatus;
027import org.nuxeo.connect.update.task.Command;
028import org.nuxeo.connect.update.task.Task;
029import org.nuxeo.connect.update.xml.XmlWriter;
030import org.w3c.dom.Element;
031
032/**
033 * Command embedding multiple commands. For internal use.
034 *
035 * @since 5.5
036 */
037public class CompositeCommand extends AbstractCommand {
038
039    public static final String ID = "composite";
040
041    protected final List<Command> commands;
042
043    protected CompositeCommand(String id) {
044        super(id);
045        commands = new ArrayList<Command>();
046    }
047
048    public CompositeCommand() {
049        super(ID);
050        commands = new ArrayList<Command>();
051    }
052
053    @Override
054    public void writeTo(XmlWriter writer) {
055        for (Command command : commands) {
056            command.writeTo(writer);
057        }
058    }
059
060    @Override
061    protected Command doRun(Task task, Map<String, String> prefs) throws PackageException {
062        CompositeCommand rollbackCommand = new CompositeCommand();
063        for (Command command : commands) {
064            rollbackCommand.addCommand(command.run(task, prefs));
065        }
066        return rollbackCommand;
067    }
068
069    @Override
070    protected void doValidate(Task task, ValidationStatus status) throws PackageException {
071        for (Command command : commands) {
072            command.validate(task, status);
073        }
074    }
075
076    @Override
077    public void readFrom(Element element) throws PackageException {
078        throw new UnsupportedOperationException("Composite command is for internal use only.");
079    }
080
081    public void addCommand(Command command) {
082        if (command != null) {
083            commands.add(command);
084        }
085    }
086
087    public boolean isEmpty() {
088        return commands.isEmpty();
089    }
090
091}