View Javadoc

1   /**
2    * This file Copyright (c) 2003-2013 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.content2bean.impl;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.NodeData;
38  import info.magnolia.cms.util.ExtendingContentWrapper;
39  import info.magnolia.cms.util.NodeDataUtil;
40  import info.magnolia.content2bean.Content2BeanException;
41  import info.magnolia.content2bean.Content2BeanProcessor;
42  import info.magnolia.content2bean.Content2BeanTransformer;
43  import info.magnolia.content2bean.PropertyTypeDescriptor;
44  import info.magnolia.content2bean.TransformationState;
45  import info.magnolia.content2bean.TypeDescriptor;
46  
47  import java.util.Collection;
48  import java.util.LinkedHashMap;
49  import java.util.Map;
50  
51  import javax.inject.Inject;
52  import javax.inject.Singleton;
53  import javax.jcr.RepositoryException;
54  
55  import info.magnolia.content2bean.TypeMapping;
56  import info.magnolia.objectfactory.ComponentProvider;
57  
58  import org.slf4j.Logger;
59  import org.slf4j.LoggerFactory;
60  
61  /**
62   * Contains the logic for traversing the hierarchy and do the calls to the transformer.
63   * @author philipp
64   * @version $Id$
65   *
66   */
67  @Singleton
68  public class Content2BeanProcessorImpl implements Content2BeanProcessor {
69      private static final Logger log = LoggerFactory.getLogger(Content2BeanProcessorImpl.class);
70  
71      private final TypeMapping typeMapping;
72  
73      private boolean forceCreation = true;
74  
75      @Inject
76      public Content2BeanProcessorImpl(TypeMapping typeMapping) {
77          this.typeMapping = typeMapping;
78      }
79  
80      @Override
81      public Object toBean(Content node, boolean recursive, final Content2BeanTransformer transformer, ComponentProvider componentProvider) throws Content2BeanException{
82          return toBean(new ExtendingContentWrapper(node), recursive, transformer, transformer.newState(), componentProvider);
83      }
84  
85      protected Object toBean(Content node, boolean recursive, Content2BeanTransformer transformer, TransformationState state, ComponentProvider componentProvider) throws Content2BeanException{
86  
87          state.pushContent(node);
88  
89          TypeDescriptor type = null;
90          try {
91              type = transformer.resolveType(typeMapping, state, componentProvider);
92          }
93          catch (Throwable e) {
94              if(isForceCreation()){
95                  log.warn("can't resolve class for node " +  node.getHandle(), e);
96              }
97              else{
98                  throw new Content2BeanException("can't resolve class for node " +  node.getHandle(), e);
99              }
100         }
101 
102         Object bean = null;
103         if(type != null){
104             state.pushType(type);
105 
106             transformer = resolveTransformer(type, transformer);
107 
108             Map<String, Object> values = toMap(node, recursive, transformer, state, componentProvider);
109 
110             try {
111                 bean = transformer.newBeanInstance(state, values, componentProvider);
112             }
113             catch (Throwable e) {
114                 if(isForceCreation()){
115                     log.warn("Can't instantiate bean for " +  node.getHandle(), e);
116                 }
117                 else{
118                     throw new Content2BeanException("Can't instantiate bean for " +  node.getHandle(), e);
119                 }
120             }
121 
122             if(bean != null){
123                 state.pushBean(bean);
124 
125                 setProperties(values, transformer, state);
126 
127                 transformer.initBean(state, values);
128 
129                 bean = state.getCurrentBean();
130 
131                 state.popBean();
132             }
133             else{
134                 if(forceCreation){
135                     log.warn("can't instantiate bean of type " + type.getType().getName() + " for node " + node.getHandle());
136                 }
137                 else{
138                     throw new Content2BeanException("can't instantiate bean of type " + type.getType().getName());
139                 }
140             }
141 
142             state.popType();
143         }
144         state.popContent();
145 
146         return bean;
147     }
148 
149     @Override
150     public Object setProperties(final Object bean, Content node, boolean recursive, Content2BeanTransformer transformer, ComponentProvider componentProvider) throws Content2BeanException {
151         // enable extending feature
152         node = new ExtendingContentWrapper(node);
153 
154         TransformationState state = transformer.newState();
155         state.pushBean(bean);
156         state.pushContent(node);
157 
158         // TODO -  MAGNOLIA-3525 TypeDescriptor type = transformer.getTypeMapping().getTypeDescriptor(bean.getClass());
159         TypeDescriptor type = typeMapping.getTypeDescriptor(bean.getClass());
160 
161         state.pushType(type);
162 
163         transformer = resolveTransformer(type, transformer);
164 
165         Map<String, Object> values = toMap(node, recursive, transformer, state, componentProvider);
166 
167         setProperties(values, transformer, state);
168 
169         transformer.initBean(state, values);
170 
171         state.popBean();
172         state.popType();
173         state.popContent();
174 
175         return bean;
176     }
177 
178     /**
179      * Transforms the children of provided content into a map.
180      */
181     protected Map<String, Object> toMap(Content node, boolean recursive, Content2BeanTransformer transformer, TransformationState state, ComponentProvider componentProvider) throws Content2BeanException {
182         Map<String, Object> map = new LinkedHashMap<String, Object>();
183         for (NodeData nd : node.getNodeDataCollection()) {
184             Object val = NodeDataUtil.getValueObject(nd);
185             if (val != null) {
186                 map.put(nd.getName(), val);
187             }
188         }
189 
190         if(recursive){
191             final Collection<Content> children = transformer.getChildren(node);
192             for (Content childNode : children) {
193                 // in case the the class can not get resolved we can use now
194                 // the parent bean to resolve the class
195 
196                 Object childBean = toBean(childNode, true, transformer, state, componentProvider);
197                 // can be null if forceCreation is true
198                 if(childBean != null){
199                     String name = childNode.getName();
200                     try {
201                         if(childNode.getIndex() > 1){
202                             name += childNode.getIndex();
203                         }
204                     }
205                     catch (RepositoryException e) {
206                         log.error("can't read index of the node [" + childNode + "]", e);
207                     }
208                     map.put(name, childBean);
209                 }
210             }
211         }
212 
213         return map;
214     }
215 
216     /**
217      * Populates the properties of the bean with values from the map.
218      * TODO in case the bean is a map / collection the transfomer.setProperty() method should be called too
219      * TODO if the bean has not a certain property but a value is present, transformer.setProperty() should be called with a fake property descriptor
220      */
221     protected void setProperties(Map<String, Object> values, final Content2BeanTransformer transformer, TransformationState state) throws Content2BeanException {
222         Object bean = state.getCurrentBean();
223         log.debug("will populate bean {} with the values {}", bean.getClass().getName(), values);
224 
225         if(bean instanceof Map){
226             ((Map<String, Object>)bean).putAll(values);
227         }
228 
229         if(bean instanceof Collection){
230             ((Collection<Object>)bean).addAll(values.values());
231         }
232 
233         else{
234             // TypeDescriptor beanTypeDescriptor = transformer.getTypeMapping().getTypeDescriptor(bean.getClass());
235             TypeDescriptor beanTypeDescriptor = typeMapping.getTypeDescriptor(bean.getClass());
236             final Collection<PropertyTypeDescriptor> dscrs = beanTypeDescriptor.getPropertyDescriptors(typeMapping).values();
237 
238             for (PropertyTypeDescriptor descriptor : dscrs) {
239                 transformer.setProperty(typeMapping, state, descriptor, values);
240             }
241         }
242     }
243 
244     protected Content2BeanTransformer resolveTransformer(TypeDescriptor type, Content2BeanTransformer transformer) {
245         Content2BeanTransformer customTransformer = type.getTransformer();
246         if(customTransformer != null){
247             transformer = customTransformer;
248         }
249         return transformer;
250     }
251 
252     public boolean isForceCreation() {
253         return this.forceCreation;
254     }
255 
256     /**
257      * @deprecated only used in tests
258      */
259     public void setForceCreation(boolean handleExceptions) {
260         this.forceCreation = handleExceptions;
261     }
262 
263 }