View Javadoc
1   /**
2    * This file Copyright (c) 2017 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.module.mail.app.field.transformer;
35  
36  import info.magnolia.jcr.util.NodeUtil;
37  import info.magnolia.ui.api.i18n.I18NAuthoringSupport;
38  import info.magnolia.ui.form.field.definition.CompositeFieldDefinition;
39  import info.magnolia.ui.form.field.definition.ConfiguredFieldDefinition;
40  import info.magnolia.ui.form.field.transformer.basic.BasicTransformer;
41  import info.magnolia.ui.vaadin.integration.jcr.JcrNodeAdapter;
42  
43  import java.lang.reflect.Modifier;
44  import java.util.ArrayList;
45  import java.util.Collection;
46  import java.util.HashMap;
47  import java.util.List;
48  import java.util.Map;
49  import java.util.stream.Collectors;
50  
51  import javax.inject.Inject;
52  import javax.jcr.Node;
53  import javax.jcr.RepositoryException;
54  
55  import org.apache.commons.lang.StringUtils;
56  
57  import com.vaadin.v7.data.Property;
58  import com.vaadin.v7.data.util.ObjectProperty;
59  import com.vaadin.v7.data.util.PropertysetItem;
60  
61  /**
62   * Transformer for {@link info.magnolia.module.mail.smtp.authentication.SmtpAuthentication}.
63   */
64  public class MailAuthenticationTransformer extends BasicTransformer<PropertysetItem> {
65  
66      private static final String AUTHENTICATION = "authentication";
67  
68      private Map<String, List<String>> fieldNames = new HashMap<>();
69  
70      @Inject
71      public MailAuthenticationTransformer(JcrNodeAdapter relatedFormItem, CompositeFieldDefinition definition, Class<PropertysetItem> type, I18NAuthoringSupport i18NAuthoringSupport) throws RepositoryException {
72          super(new AuthenticationConfigurationAdapter(relatedFormItem), definition, type, i18NAuthoringSupport);
73          List<ConfiguredFieldDefinition> fields = definition.getFields();
74          fields.forEach(field -> {
75              if (field instanceof CompositeFieldDefinition && field.getName() != null) {
76                  if (!fieldNames.containsKey(field.getName())) {
77                      fieldNames.put(field.getName(), new ArrayList<>());
78                  }
79                  fieldNames.get(field.getName()).addAll(((CompositeFieldDefinition) field).getFieldNames());
80              }
81          });
82      }
83  
84      @Override
85      public void writeToItem(PropertysetItem newValues) {
86          for (Object id : newValues.getItemPropertyIds()) {
87              String propertyName = (String) id;
88              if (fieldNames.containsKey(propertyName)) {
89                  PropertysetItem values = (PropertysetItem) newValues.getItemProperty(propertyName).getValue();
90  
91                  for (Object ida : values.getItemPropertyIds()) {
92                      String name = (String) ida;
93                      Property<?> property = relatedFormItem.getItemProperty(name);
94                      if (property == null || property.getValue() == null) {
95                          relatedFormItem.addItemProperty(name, values.getItemProperty(name));
96                      }
97                  }
98              }
99          }
100         // This stores the selected option
101         String propertyName = definePropertyName();
102         if (newValues.getItemProperty(propertyName) != null) {
103             relatedFormItem.addItemProperty(propertyName, newValues.getItemProperty(propertyName));
104         }
105     }
106 
107     @Override
108     public PropertysetItem readFromItem() {
109         PropertysetItem newValue = new PropertysetItem();
110         fieldNames.forEach((compositeKeyName, fields) -> {
111             PropertysetItem compositeFieldNewValues = new PropertysetItem();
112             fields.forEach(propertyName -> {
113                 if (relatedFormItem.getItemProperty(propertyName) != null) {
114                     compositeFieldNewValues.addItemProperty(propertyName, relatedFormItem.getItemProperty(propertyName));
115                 }
116             });
117             newValue.addItemProperty(compositeKeyName, new ObjectProperty<>(compositeFieldNewValues, PropertysetItem.class));
118         });
119         newValue.addItemProperty(AUTHENTICATION, relatedFormItem.getItemProperty("class") == null ? new ObjectProperty<>(StringUtils.EMPTY) : relatedFormItem.getItemProperty("class"));
120         return newValue;
121     }
122 
123     private static class AuthenticationConfigurationAdapter extends JcrNodeAdapter {
124 
125         private AuthenticationConfigurationAdapter(JcrNodeAdapter parent) throws RepositoryException {
126             super(getAuthenticationNode(parent));
127             parent.addChild(this);
128         }
129 
130         private static Node getAuthenticationNode(JcrNodeAdapter parent) throws RepositoryException {
131             return NodeUtil.createPath(parent.getJcrItem(), AUTHENTICATION, parent.getPrimaryNodeTypeName(), true);
132         }
133 
134         @Override
135         protected void updateProperty(javax.jcr.Item item, String propertyId, Property property) {
136             try {
137                 if (AUTHENTICATION.equals(propertyId)) {
138                     super.updateProperty(item, "class", property);
139                 } else if (getAuthenticationClassProperties().contains(propertyId)) {
140                     super.updateProperty(item, propertyId, property);
141                 } else if (getChangedProperties().containsKey(AUTHENTICATION)) {
142                     final Node node = (Node) item;
143                     if (node.hasProperty(propertyId)) {
144                         node.getProperty(propertyId).remove();
145                     }
146                 }
147             } catch (RepositoryException | ClassNotFoundException e) {
148                 throw new RuntimeException(e);
149             }
150         }
151 
152         private Collection<String> getAuthenticationClassProperties() throws ClassNotFoundException {
153             return !getChangedProperties().containsKey(AUTHENTICATION) ? new ArrayList<>() :
154                     java.util.Arrays.stream(Class.forName((String) getChangedProperties().get(AUTHENTICATION).getValue()).getDeclaredFields())
155                     .filter(field -> !Modifier.isFinal(field.getModifiers()))
156                     .map(field -> StringUtils.substringAfterLast(field.toString(), "."))
157                     .collect(Collectors.toList());
158         }
159     }
160 }