View Javadoc
1   /**
2    * This file Copyright (c) 2013-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.ui.form.field.definition;
35  
36  import info.magnolia.ui.api.app.AppDescriptor;
37  import info.magnolia.ui.form.AbstractFormKeyGenerator;
38  import info.magnolia.ui.form.definition.FormDefinition;
39  import info.magnolia.ui.form.definition.TabDefinition;
40  
41  import java.lang.reflect.AnnotatedElement;
42  import java.lang.reflect.Method;
43  import java.util.Deque;
44  import java.util.LinkedList;
45  import java.util.List;
46  import java.util.Optional;
47  
48  import org.apache.commons.lang3.StringUtils;
49  import org.slf4j.Logger;
50  import org.slf4j.LoggerFactory;
51  
52  /**
53   * An {@link info.magnolia.i18nsystem.I18nKeyGenerator} for {@link FieldDefinition}.
54   */
55  public class FieldDefinitionKeyGenerator extends AbstractFormKeyGenerator<FieldDefinition> {
56  
57      private static final Logger log = LoggerFactory.getLogger(FieldDefinitionKeyGenerator.class);
58  
59      private static final String CHOOSE_DIALOG_DEFINITION = "ChooseDialogDefinition";
60  
61      @Override
62      protected void keysFor(List<String> list, FieldDefinition field, AnnotatedElement el) {
63          Object parent = getParentViaCast(field);
64          final String fieldName = field.getName().replace(':', '-');
65          final String fieldOrGetterName = fieldOrGetterName(el);
66  
67          if (parent != null && isChooseDialog(parent.getClass())) {
68              // handle choose dialog
69              final AppDescriptor app = (AppDescriptor) getRoot(field);
70              addKey(list, app.getName(), CHOOSE_DIALOG, FIELDS, fieldName, fieldOrGetterName);
71          } else {
72              final Deque<String> parentNames = new LinkedList<>();
73              while (parent != null && !(parent instanceof TabDefinition)) {
74                  getParentName(parent).ifPresent(parentNames::addFirst);
75                  parent = getParentViaCast(parent);
76              }
77              final String parentKeyPart = StringUtils.join(parentNames, '.').replace(':', '-');
78  
79              if (parent instanceof TabDefinition) {
80  
81                  TabDefinition tab = (TabDefinition) parent;
82                  final String tabName = tab.getName();
83                  final FormDefinition formDef = getParentViaCast(tab);
84                  final String rawDialogID = getIdOrNameForUnknownRoot(formDef, false);
85                  final String dialogID = keyify(rawDialogID);
86  
87                  // in case of a field in field
88                  if (parentNames.size() > 0) {
89                      // <dialogId>.<tabName>.<parentFieldNames_separated_by_dots>.<fieldName>.<property>
90                      // <dialogId>.<tabName>.<parentFieldNames_separated_by_dots>.<fieldName> (in case of property==label)
91                      addKey(list, true, dialogID, tabName, parentKeyPart, fieldName, fieldOrGetterName);
92                  }
93                  // <dialogId>.<tabName>.<fieldName>.<property>
94                  // <dialogId>.<tabName>.<fieldName> (in case of property==label)
95                  addKey(list, dialogID, tabName, fieldName, fieldOrGetterName);
96                  // <tabName>.<fieldName> (in case of property==label)
97                  addKey(list, tabName, fieldName, fieldOrGetterName);
98                  // <dialogId>.<fieldName>.<property>
99                  // <dialogId>.<fieldName> (in case property==label)
100                 addKey(list, dialogID, fieldName, fieldOrGetterName);
101                 String[] parts = StringUtils.split(dialogID, ".");
102                 if (parts.length > 1) {
103                     String dialogIDNoModuleName = parts[parts.length - 1];
104                     addKey(list, dialogIDNoModuleName, fieldName, fieldOrGetterName);
105                     addKey(list, dialogIDNoModuleName, tabName, fieldName, fieldOrGetterName);
106                 }
107             } else {
108                 // In case we didn't encounter parent tab definition - we simply generated a key based on dot-separated parent names
109                 addKey(list, parentKeyPart, fieldName, fieldOrGetterName);
110             }
111         }
112         addKey(list, FIELDS, fieldName, fieldOrGetterName);
113     }
114 
115     /**
116      * Dirty hack, as the ChooseDialogDefinition is defined in dependent module.
117      */
118     private boolean isChooseDialog(Class<?> clazz) {
119         /**
120          * We can't really use something smarter than the current implementation due to following reasons:
121          * -  Fetching the ChooseDialogDefinition class with reflection and using Class#isAssignableFrom is practically impossible to test
122          * (test classes can't access ChooseDialogDefinition).
123          * - Using String#endsWith() is not feasible because enhancer appends its suffix to the class name.
124          */
125         return clazz.getSimpleName().contains(CHOOSE_DIALOG_DEFINITION);
126     }
127 
128     /**
129      * TODO - this method has to be considered for removal in favour of using the {@link AbstractFormKeyGenerator#getIdOrNameForUnknownRoot(Object)}.
130      *
131      * @see <a href="http://jira.magnolia-cms.com/browse/MGNLUI-4169">MGNLUI-4169</a>
132      */
133     private Optional<String> getParentName(Object parent) {
134         try {
135             Method getNameMethod = parent.getClass().getMethod("getName");
136             return Optional.of((String) getNameMethod.invoke(parent));
137         } catch (NoSuchMethodException e) {
138             // TODO - at this point the exception could be avoided if AbstractFormKeyGenerator#getIdOrNameForUnknownRoot(Object) was used
139             log.debug("Failed to obtain the name property value of an object [{}]: {}", parent, e.getMessage());
140         } catch (ReflectiveOperationException e) {
141             log.warn("Failed to obtain the name property value of an object [{}]: {}", parent, e.getMessage());
142         }
143         return Optional.empty();
144     }
145 }