001package org.nasdanika.emf;
002
003import org.eclipse.emf.ecore.EObject;
004import org.nasdanika.common.CommandFactory;
005import org.nasdanika.common.Consumer;
006import org.nasdanika.common.ConsumerFactory;
007import org.nasdanika.common.Context;
008import org.nasdanika.common.NasdanikaException;
009import org.nasdanika.common.ProgressMonitor;
010
011/**
012 * Base class for commands which execute models by adapting them to a specific adapter type and then
013 * adapting that adapter to {@link CommandFactory}.
014 * @author Pavel
015 *
016 * @param <T>
017 * @param <A>
018 */
019public abstract class AdapterModelCommand<T extends EObject, A> extends ModelCommand<T> {
020        
021        /**
022         * @return Type of the adapter used to execute the model.
023         */
024        protected abstract Class<A> getAdapterType();
025        
026        protected abstract CommandFactory createCommandFactory(A adapter);
027
028        @Override
029        protected ConsumerFactory<T> getConsumerFactory() {
030                return new ConsumerFactory<T>() {
031
032                        @Override
033                        public Consumer<T> create(Context context) {
034                                return new Consumer<T>() {
035
036                                        @Override
037                                        public double size() {
038                                                return 1;
039                                        }
040
041                                        @Override
042                                        public String name() {
043                                                return "Adapt and execute";
044                                        }
045
046                                        @Override
047                                        public void execute(T element, ProgressMonitor progressMonitor) {
048                                                A adapter = EObjectAdaptable.adaptTo(element, getAdapterType());
049                                                if (adapter == null) {
050                                                        throw new NasdanikaException("Cannot adapt " + element + " to " + getAdapterType());
051                                                }
052                                                CommandFactory cf = createCommandFactory(adapter);
053                                                org.nasdanika.common.Command command = cf.create(context);
054                                                command.splitAndExecute(size(), progressMonitor);
055                                        }
056                                        
057                                };
058                        }
059                };
060        }
061
062}