View Javadoc
1   /**
2    * This file Copyright (c) 2003-2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.commands;
35  
36  import info.magnolia.cms.util.DeprecationUtil;
37  import info.magnolia.cms.util.ModuleConfigurationObservingManager;
38  import info.magnolia.commands.chain.Catalog;
39  import info.magnolia.commands.chain.Command;
40  import info.magnolia.commands.chain.Context;
41  import info.magnolia.context.SimpleContext;
42  import info.magnolia.event.EventBus;
43  import info.magnolia.event.SystemEventBus;
44  import info.magnolia.jcr.node2bean.Node2BeanException;
45  import info.magnolia.jcr.node2bean.Node2BeanProcessor;
46  import info.magnolia.jcr.util.NodeTypes;
47  import info.magnolia.jcr.util.NodeUtil;
48  import info.magnolia.module.ModuleRegistry;
49  import info.magnolia.module.ModulesStartedEvent;
50  import info.magnolia.objectfactory.Components;
51  
52  import java.util.HashMap;
53  import java.util.Iterator;
54  import java.util.List;
55  import java.util.Map;
56  import java.util.concurrent.atomic.AtomicReference;
57  
58  import javax.inject.Inject;
59  import javax.inject.Named;
60  import javax.inject.Singleton;
61  import javax.jcr.Node;
62  import javax.jcr.RepositoryException;
63  
64  import org.apache.commons.lang3.StringUtils;
65  import org.slf4j.Logger;
66  import org.slf4j.LoggerFactory;
67  
68  
69  /**
70   * Manages configured commands and command catalogs and performs execution of commands. Monitors configuration
71   * of commands and catalogs in JCR within each module under a node named <code>commands</code>.
72   *
73   * @see Catalog
74   * @see Command
75   */
76  @Singleton
77  public class CommandsManager extends ModuleConfigurationObservingManager {
78  
79      private static final Logger log = LoggerFactory.getLogger(CommandsManager.class);
80  
81      public static final String DEFAULT_CATALOG = "default";
82  
83      public static final String COMMAND_DELIM = "-";
84  
85      private final CommandTransformer commandTransformer;
86  
87      private final Node2BeanProcessor nodeToBean;
88  
89      /**
90       * Atomic reference to a map containing the catalogs in use. For thread safety the map must never be changed and is
91       * replaced entirely when something is changed in the JCR.
92       */
93      private final AtomicReference<Map<String, MgnlCatalog>> catalogs = new AtomicReference<Map<String, MgnlCatalog>>(new HashMap<String, MgnlCatalog>());
94  
95      @Inject
96      public CommandsManager(ModuleRegistry moduleRegistry, Node2BeanProcessor nodeToBean, @Named(SystemEventBus.NAME) EventBus systemEventBus) {
97          super("commands", moduleRegistry);
98          this.nodeToBean = nodeToBean;
99          this.commandTransformer = new CommandTransformer();
100         systemEventBus.addHandler(ModulesStartedEvent.class, new ModulesStartedEvent.Handler() {
101             @Override
102             public void onModuleStartupCompleted(ModulesStartedEvent event) {
103                 CommandsManager.this.start();
104             }
105         });
106     }
107 
108     /**
109      * @deprecated since 5.4.5 use {@link #CommandsManager(ModuleRegistry, Node2BeanProcessor, EventBus)}
110      */
111     @Deprecated
112     public CommandsManager(Node2BeanProcessor nodeToBean) {
113         this(Components.getComponent(ModuleRegistry.class), nodeToBean, Components.getComponentWithAnnotation(EventBus.class, Components.named(SystemEventBus.NAME)));
114     }
115 
116     @Override
117     protected void reload(List<Node> nodes) throws RepositoryException {
118         Map<String, MgnlCatalog> foundCatalogs = new HashMap<>();
119         for (Node node : nodes) {
120             registerCatalogs(node, foundCatalogs);
121         }
122         this.catalogs.set(foundCatalogs);
123     }
124 
125     protected void registerCatalogs(Node node, Map<String, MgnlCatalog> catalogs) throws RepositoryException {
126         // is this a catalog or a collection of catalogs?
127         Iterator<Node> children = NodeUtil.getNodes(node, NodeTypes.Content.NAME).iterator();
128         if (!children.hasNext()) {
129             registerCatalog(node, catalogs);
130         } else {
131             while (children.hasNext()) {
132                 registerCatalogs(children.next(), catalogs);
133             }
134         }
135     }
136 
137     protected void registerCatalog(Node node, Map<String, MgnlCatalog> catalogs) {
138         try {
139             log.debug("Registering commands at {}...", node.getPath());
140             MgnlCatalog../info/magnolia/commands/MgnlCatalog.html#MgnlCatalog">MgnlCatalog catalog = (MgnlCatalog) nodeToBean.toBean(node, true, commandTransformer, Components.getComponentProvider());
141             MgnlCatalog current = catalogs.get(catalog.getName());
142             if (current == null) {
143                 catalogs.put(catalog.getName(), catalog);
144                 log.info("Catalog [{}] registered: {}", catalog.getName(), catalog);
145             } else {
146                 for (String commandName : catalog.getNames()) {
147                     Command command = current.getCommand(commandName);
148                     if (command != null) {
149                         log.warn(String.format("Command [%s] found at [%s] already exists in the catalog [%s], skipping...", commandName, node.getPath(), current.getName()));
150                     } else {
151                         log.info("Adding new command [{}] to already registered catalog [{}]...", commandName, current.getName());
152                         current.addCommand(commandName, catalog.getCommand(commandName));
153                     }
154                 }
155             }
156         } catch (RepositoryException e) {
157             log.error("Can't read catalog [{}]", node, e);
158         } catch (Node2BeanException e) {
159             log.error("Can't create catalog [{}]", node, e);
160         }
161     }
162 
163     /**
164      * Get the command.
165      *
166      * @param catalogName the catalog containing the command
167      * @param commandName the name of the command
168      * @return the command to execute
169      */
170     public Command getCommand(String catalogName, String commandName) {
171         // if empty catalog name, use default catalog
172         MgnlCatalog catalog = catalogs.get().get(StringUtils.isNotEmpty(catalogName) ? catalogName : DEFAULT_CATALOG);
173         if (catalog != null) {
174             Command command = catalog.getCommand(commandName);
175             if (command != null) {
176                 try {
177                     return command.clone();
178                 } catch (CloneNotSupportedException e) {
179                     log.warn("Cannot create clone of command [{}] from catalog [{}], because command doesn't support the Cloneable interface", commandName, catalogName);
180                 }
181             }
182         }
183 
184         return null;
185     }
186 
187     /**
188      * Use a delimiter to separate the catalog and command name.
189      */
190     public Command getCommand(String commandName) {
191         String catalogName = DEFAULT_CATALOG;
192         if (StringUtils.contains(commandName, COMMAND_DELIM)) {
193             catalogName = StringUtils.substringBefore(commandName, COMMAND_DELIM);
194             commandName = StringUtils.substringAfter(commandName, COMMAND_DELIM);
195         }
196 
197         Command command = getCommand(catalogName, commandName);
198         if (command == null) {
199             command = getCommand(DEFAULT_CATALOG, commandName);
200         }
201         return command;
202     }
203 
204     /**
205      * @return Returns the instance.
206      * @deprecated since 4.5, use IoC !
207      */
208     @Deprecated
209     public static CommandsManager getInstance() {
210         return Components.getComponent(CommandsManager.class);
211     }
212 
213     /**
214      * Executes the given command in the given catalog with the given parameters.
215      *
216      * @throws Exception if an error occurs during execution or if the command could not be found in any catalog
217      */
218     public boolean executeCommand(final String catalogName, final String commandName, final Map<String, Object> params) throws Exception {
219         final Command command = getCommand(catalogName, commandName);
220         if (command == null) {
221             throw new Exception(String.format("Command [%s] could not be found in catalog [%s]", commandName, catalogName));
222         }
223         log.debug("Executing command [{}] from catalog [{}] and params [{}]...", commandName, catalogName, params);
224         return executeCommand(command, params);
225     }
226 
227     /**
228      * Executes the given command in the default catalog with the given parameters.
229      *
230      * @throws Exception if an error occurs during execution or if the command could not be found in any catalog
231      * @see CommandsManager#executeCommand(String, String, Map)
232      */
233     public boolean executeCommand(final String commandName, final Map<String, Object> params) throws Exception {
234         return executeCommand(DEFAULT_CATALOG, commandName, params);
235     }
236 
237     /**
238      * Executes the given command with the given parameters.
239      *
240      * @throws Exception if an error occurs during execution or if the command could not be found in any catalog
241      * @see CommandsManager#executeCommand(String, Map)
242      */
243     public boolean executeCommand(final Command command, final Map<String, Object> params) throws Exception {
244         return executeCommand(command, params, new SimpleContext());
245     }
246 
247     /**
248      * Executes the given command with given context.
249      *
250      * @see CommandsManager#executeCommand(String, Map)
251      */
252     public boolean executeCommand(final Command command, final Map<String, Object> params, Context context) throws Exception {
253         if (params != null) {
254             context.putAll(params);
255         }
256         return command.execute(context);
257     }
258 
259     Catalog getCatalogByName(String name) {
260         return catalogs.get().get(name);
261     }
262 
263     /**
264      * @deprecated since 5.4.5. This should not be public but only protected. Use {@link super#reload()} instead.
265      */
266     @Deprecated
267     @Override
268     public synchronized void reload() {
269         DeprecationUtil.isDeprecated("Use reload() instead");
270         super.reload();
271     }
272 
273     /**
274      * @deprecated since 5.4.5. Use {@link #onClear()} instead.
275      */
276     @Deprecated
277     public void clear() {
278         DeprecationUtil.isDeprecated("Use onClear() instead.");
279         try {
280             this.onClear();
281         } catch (RepositoryException e) {
282             log.error(e.getMessage(), e);
283         }
284     }
285 }