View Javadoc
1   /**
2    * This file Copyright (c) 2011-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.factory;
35  
36  import static info.magnolia.ui.framework.app.contenttypes.AppWithContentType.CONTENT_TYPE_REFERENCE_PREFIX;
37  
38  import info.magnolia.annotation.deprecation.MgnlDeprecated;
39  import info.magnolia.config.registry.DefinitionProvider;
40  import info.magnolia.objectfactory.ComponentProvider;
41  import info.magnolia.objectfactory.Components;
42  import info.magnolia.ui.api.app.AppContext;
43  import info.magnolia.ui.api.app.AppController;
44  import info.magnolia.ui.api.app.AppDescriptor;
45  import info.magnolia.ui.api.app.ChooseDialogCallback;
46  import info.magnolia.ui.api.app.SubAppContext;
47  import info.magnolia.ui.contentapp.contenttypes.ContentTypeAppDescriptor;
48  import info.magnolia.ui.api.app.registry.AppDescriptorRegistry;
49  import info.magnolia.ui.api.context.UiContext;
50  import info.magnolia.ui.api.i18n.I18NAuthoringSupport;
51  import info.magnolia.ui.form.field.LinkField;
52  import info.magnolia.ui.form.field.component.ContentPreviewComponent;
53  import info.magnolia.ui.form.field.converter.IdentifierToPathConverter;
54  import info.magnolia.ui.form.field.converter.Vaadin7FieldValueConverterAdapter;
55  import info.magnolia.ui.form.field.definition.LinkFieldDefinition;
56  import info.magnolia.ui.vaadin.integration.jcr.JcrItemId;
57  import info.magnolia.ui.vaadin.integration.jcr.JcrItemUtil;
58  
59  import java.util.Objects;
60  import java.util.Optional;
61  
62  import javax.inject.Inject;
63  import javax.jcr.Node;
64  import javax.jcr.RepositoryException;
65  
66  import org.apache.commons.lang3.StringUtils;
67  import org.slf4j.Logger;
68  import org.slf4j.LoggerFactory;
69  
70  import com.vaadin.ui.Button;
71  import com.vaadin.v7.data.Item;
72  import com.vaadin.v7.data.Property;
73  import com.vaadin.v7.ui.Field;
74  
75  /**
76   * Creates and initializes a LinkField field based on a field definition.
77   *
78   * @param <D> definition type
79   * @deprecated since 6.0, please use {@link info.magnolia.ui.field.factory.LinkFieldFactory} instead.
80   */
81  @MgnlDeprecated(since = "6.0")
82  public class LinkFieldFactory<D extends LinkFieldDefinition> extends AbstractFieldFactory<D, String> {
83  
84      private static final Logger log = LoggerFactory.getLogger(LinkFieldFactory.class);
85  
86      public static final String PATH_PROPERTY_NAME = "transientPathProperty";
87      public static final String SELF_APP_REFERENCE = "self";
88  
89      private final AppController appController;
90      private final UiContext uiContext;
91      private final AppDescriptorRegistry appRegistry;
92  
93      private ComponentProvider componentProvider;
94      private LinkField linkField;
95  
96  
97      @Inject
98      public LinkFieldFactory(D definition, Item relatedFieldItem, UiContext uiContext, I18NAuthoringSupport i18nAuthoringSupport, AppController appController, ComponentProvider componentProvider, AppDescriptorRegistry appRegistry) {
99          super(definition, relatedFieldItem, uiContext, i18nAuthoringSupport);
100         this.appController = appController;
101         this.uiContext = uiContext;
102         this.componentProvider = componentProvider;
103         this.appRegistry = appRegistry;
104     }
105 
106     /**
107      * @deprecated since 5.7.2, use {@link #LinkFieldFactory(LinkFieldDefinition, Item, UiContext, I18NAuthoringSupport, AppController, ComponentProvider, AppDescriptorRegistry)}
108      */
109     @Deprecated
110     public LinkFieldFactory(D definition, Item relatedFieldItem, UiContext uiContext, I18NAuthoringSupport i18nAuthoringSupport, AppController appController, ComponentProvider componentProvider) {
111         this(definition, relatedFieldItem, uiContext, i18nAuthoringSupport, appController, componentProvider, Components.getComponent(AppDescriptorRegistry.class));
112     }
113 
114     @Override
115     public void setComponentProvider(ComponentProvider componentProvider) {
116         super.setComponentProvider(componentProvider);
117         this.componentProvider = componentProvider;
118     }
119 
120     @Override
121     protected Field<String> createFieldComponent() {
122         linkField = new LinkField();
123         // Set Caption
124         linkField.setButtonCaptionNew(isMessageKey(definition.getButtonSelectNewLabel()) ? definition.getButtonSelectNewDefaultLabel() : definition.getButtonSelectNewLabel());
125         linkField.setButtonCaptionOther(isMessageKey(definition.getButtonSelectOtherLabel()) ? definition.getButtonSelectOtherDefaultLabel() : definition.getButtonSelectOtherLabel());
126         linkField.getSelectButton().setDisableOnClick(true);
127         // Add a callback listener on the select button
128         linkField.getSelectButton().addClickListener(createButtonClickListener());
129         linkField.setFieldEditable(definition.isFieldEditable());
130 
131         IdentifierToPathConverter converter = definition.getIdentifierToPathConverter();
132         if (converter != null) {
133             converter.setWorkspaceName(definition.getTargetWorkspace());
134             linkField.setTextFieldConverter(Vaadin7FieldValueConverterAdapter.wrap(converter));
135         }
136 
137         // Register the content preview if it's defined.
138         if (definition.getContentPreviewDefinition() != null && definition.getContentPreviewDefinition().getContentPreviewClass() != null) {
139             final ContentPreviewComponent<?> contentPreviewComponent = componentProvider.newInstance(definition.getContentPreviewDefinition().getContentPreviewClass(), definition.getTargetWorkspace());
140             linkField.getTextField().addValueChangeListener((Property.ValueChangeListener) event -> {
141                 String itemReference = Objects.toString(event.getProperty().getValue(), StringUtils.EMPTY);
142                 contentPreviewComponent.onValueChange(itemReference);
143                 contentPreviewComponent.setVisible(StringUtils.isNotBlank(itemReference));
144             });
145             contentPreviewComponent.onValueChange(linkField.getValue());
146             contentPreviewComponent.setVisible(StringUtils.isNotBlank(linkField.getValue()));
147             linkField.setContentPreview(contentPreviewComponent);
148         }
149 
150         String placeholder = definition.getPlaceholder();
151         if (placeholder != null && !isMessageKey(placeholder)) {
152             linkField.getTextField().setInputPrompt(placeholder);
153         }
154 
155         return linkField;
156     }
157 
158     /**
159      * Create the Button click Listener. On click: Create a Dialog and
160      * Initialize callback handling.
161      */
162     private Button.ClickListener createButtonClickListener() {
163         return (Button.ClickListener) event -> {
164             ChooseDialogCallback callback = createChooseDialogCallback();
165             String value = linkField.getTextField().getValue();
166 
167             String appName = definition.getAppName();
168             if (SELF_APP_REFERENCE.equalsIgnoreCase(appName)) {
169                 appName = resolveCurrentAppName().orElse(appName);
170             } else if (StringUtils.startsWith(appName, CONTENT_TYPE_REFERENCE_PREFIX)) {
171                 appName = resolveContentTypeAppName(appName).orElse(appName);
172             }
173             if (StringUtils.isNotBlank(definition.getTargetTreeRootPath())) {
174                 appController.openChooseDialog(appName, uiContext, definition.getTargetTreeRootPath(), value, callback);
175             } else {
176                 appController.openChooseDialog(appName, uiContext, value, callback);
177             }
178         };
179     }
180 
181     private Optional<String> resolveCurrentAppName() {
182         if (uiContext instanceof SubAppContext) {
183             return Optional.of(((SubAppContext) uiContext).getAppContext().getName());
184         } else if (uiContext instanceof AppContext) {
185             return Optional.ofNullable(((AppContext) uiContext).getName());
186         }
187         // Wot then? not gonna infer harder
188         log.warn("Attempting to resolve linkField '{}' appName self-reference without actually being in an app", definition.getName());
189         return Optional.empty();
190     }
191 
192     private Optional<String> resolveContentTypeAppName(String appName) {
193         String contentType = StringUtils.removeStart(appName, CONTENT_TYPE_REFERENCE_PREFIX);
194 
195         return appRegistry.getAllProviders().stream()
196                 .filter(DefinitionProvider::isValid)
197                 .map(DefinitionProvider::get)
198                 .filter(ContentTypeAppDescriptor.class::isInstance)
199                 .map(ContentTypeAppDescriptor.class::cast)
200                 .filter(appDescriptor -> StringUtils.equalsIgnoreCase(contentType, appDescriptor.getContentType()))
201                 .findFirst()
202                 .map(AppDescriptor::getName);
203     }
204 
205     /**
206      * @return specific {@link ChooseDialogCallback} implementation used to process the selected value.
207      */
208     protected ChooseDialogCallback createChooseDialogCallback() {
209         return new ChooseDialogCallback() {
210 
211             @Override
212             public void onItemChosen(String actionName, final Object chosenValue) {
213                 String newValue = null;
214                 if (chosenValue instanceof JcrItemId) {
215                     String propertyName = definition.getTargetPropertyToPopulate();
216                     try {
217                         javax.jcr.Item jcrItem = JcrItemUtil.getJcrItem((JcrItemId) chosenValue);
218                         if (jcrItem.isNode()) {
219                             final Node selected = (Node) jcrItem;
220                             boolean isPropertyExisting = StringUtils.isNotBlank(propertyName) && selected.hasProperty(propertyName);
221                             newValue = isPropertyExisting ? selected.getProperty(propertyName).getString() : selected.getPath();
222                         }
223                     } catch (RepositoryException e) {
224                         log.error("Not able to access the configured property. Value will not be set.", e);
225                     }
226                 } else {
227                     newValue = String.valueOf(chosenValue);
228                 }
229                 linkField.setValue(newValue);
230                 linkField.getSelectButton().setEnabled(true);
231             }
232 
233             @Override
234             public void onCancel() {
235                 linkField.getSelectButton().setEnabled(true);
236             }
237         };
238     }
239 }