aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/yaml/snakeyaml/TypeDescription.java
blob: e65308b1971a675d7c99f628bcf2150458cf039f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/**
 * Copyright (c) 2008, SnakeYAML
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package org.yaml.snakeyaml;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.introspector.BeanAccess;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.introspector.PropertySubstitute;
import org.yaml.snakeyaml.introspector.PropertyUtils;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.Tag;

/**
 * Provides additional runtime information necessary to create a custom Java instance.
 *
 * In general this class is thread-safe and can be used as a singleton, the only exception being the
 * PropertyUtils field. A singleton PropertyUtils should be constructed and shared between all YAML
 * Constructors used if a singleton TypeDescription is used, since Constructor sets its
 * propertyUtils to the TypeDescription that is passed to it, hence you may end up in a situation
 * when propertyUtils in TypeDescription is from different Constructor.
 */
public class TypeDescription {

  final static private Logger log = Logger.getLogger(TypeDescription.class.getPackage().getName());

  private final Class<? extends Object> type;

  // class that implements the described type; if set, will be used as a source for constructor.
  // If not set - TypeDescription will leave instantiation of an entity to the YAML Constructor
  private Class<?> impl;

  private Tag tag;

  private transient Set<Property> dumpProperties;
  private transient PropertyUtils propertyUtils;
  private transient boolean delegatesChecked;

  private Map<String, PropertySubstitute> properties = Collections.emptyMap();

  protected Set<String> excludes = Collections.emptySet();
  protected String[] includes = null;
  protected BeanAccess beanAccess;

  public TypeDescription(Class<? extends Object> clazz, Tag tag) {
    this(clazz, tag, null);
  }

  public TypeDescription(Class<? extends Object> clazz, Tag tag, Class<?> impl) {
    this.type = clazz;
    this.tag = tag;
    this.impl = impl;
    beanAccess = null;
  }

  public TypeDescription(Class<? extends Object> clazz, String tag) {
    this(clazz, new Tag(tag), null);
  }

  public TypeDescription(Class<? extends Object> clazz) {
    this(clazz, new Tag(clazz), null);
  }

  public TypeDescription(Class<? extends Object> clazz, Class<?> impl) {
    this(clazz, new Tag(clazz), impl);
  }

  /**
   * Get tag which shall be used to load or dump the type (class).
   *
   * @return tag to be used. It may be a tag for Language-Independent Types
   *         (http://www.yaml.org/type/)
   */
  public Tag getTag() {
    return tag;
  }

  /**
   * Set tag to be used dump the type (class).
   *
   * @param tag - local or global tag
   * @deprecated it will be removed because it is not used
   */
  @Deprecated
  public void setTag(Tag tag) {
    this.tag = tag;
  }

  /**
   * Set tag to be used to dump the type (class).
   *
   * @param tag - local or global tag
   * @deprecated it will be removed because it is not used
   */
  @Deprecated
  public void setTag(String tag) {
    setTag(new Tag(tag));
  }

  /**
   * Get represented type (class)
   *
   * @return type (class) to be described.
   */
  public Class<? extends Object> getType() {
    return type;
  }

  /**
   * Specify that the property is a type-safe <code>List</code>.
   *
   * @param property name of the JavaBean property
   * @param type class of List values
   */
  @Deprecated
  public void putListPropertyType(String property, Class<? extends Object> type) {
    addPropertyParameters(property, type);
  }

  /**
   * Get class of List values for provided JavaBean property.
   *
   * @param property property name
   * @return class of List values
   */
  @Deprecated
  public Class<? extends Object> getListPropertyType(String property) {
    if (properties.containsKey(property)) {
      Class<?>[] typeArguments = properties.get(property).getActualTypeArguments();
      if (typeArguments != null && typeArguments.length > 0) {
        return typeArguments[0];
      }
    }
    return null;
  }

  /**
   * Specify that the property is a type-safe <code>Map</code>.
   *
   * @param property property name of this JavaBean
   * @param key class of keys in Map
   * @param value class of values in Map
   */
  @Deprecated
  public void putMapPropertyType(String property, Class<? extends Object> key,
      Class<? extends Object> value) {
    addPropertyParameters(property, key, value);
  }

  /**
   * Get keys type info for this JavaBean
   *
   * @param property property name of this JavaBean
   * @return class of keys in the Map
   */
  @Deprecated
  public Class<? extends Object> getMapKeyType(String property) {
    if (properties.containsKey(property)) {
      Class<?>[] typeArguments = properties.get(property).getActualTypeArguments();
      if (typeArguments != null && typeArguments.length > 0) {
        return typeArguments[0];
      }
    }
    return null;
  }

  /**
   * Get values type info for this JavaBean
   *
   * @param property property name of this JavaBean
   * @return class of values in the Map
   */
  @Deprecated
  public Class<? extends Object> getMapValueType(String property) {
    if (properties.containsKey(property)) {
      Class<?>[] typeArguments = properties.get(property).getActualTypeArguments();
      if (typeArguments != null && typeArguments.length > 1) {
        return typeArguments[1];
      }
    }
    return null;
  }

  /**
   * Adds new substitute for property <code>pName</code> parameterized by <code>classes</code> to
   * this <code>TypeDescription</code>. If <code>pName</code> has been added before - updates
   * parameters with <code>classes</code>.
   *
   * @param pName - parameter name
   * @param classes - parameterized by
   */
  public void addPropertyParameters(String pName, Class<?>... classes) {
    if (!properties.containsKey(pName)) {
      substituteProperty(pName, null, null, null, classes);
    } else {
      PropertySubstitute pr = properties.get(pName);
      pr.setActualTypeArguments(classes);
    }

  }

  @Override
  public String toString() {
    return "TypeDescription for " + getType() + " (tag='" + getTag() + "')";
  }

  private void checkDelegates() {
    Collection<PropertySubstitute> values = properties.values();
    for (PropertySubstitute p : values) {
      try {
        p.setDelegate(discoverProperty(p.getName()));
      } catch (YAMLException e) {
      }
    }
    delegatesChecked = true;
  }

  private Property discoverProperty(String name) {
    if (propertyUtils != null) {
      if (beanAccess == null) {
        return propertyUtils.getProperty(type, name);
      }
      return propertyUtils.getProperty(type, name, beanAccess);
    }
    return null;
  }

  public Property getProperty(String name) {
    if (!delegatesChecked) {
      checkDelegates();
    }
    return properties.containsKey(name) ? properties.get(name) : discoverProperty(name);
  }

  /**
   * Adds property substitute for <code>pName</code>
   *
   * @param pName property name
   * @param pType property type
   * @param getter method name for getter
   * @param setter method name for setter
   * @param argParams actual types for parameterized type (List&lt;?&gt;, Map&lt;?&gt;)
   */
  public void substituteProperty(String pName, Class<?> pType, String getter, String setter,
      Class<?>... argParams) {
    substituteProperty(new PropertySubstitute(pName, pType, getter, setter, argParams));
  }

  public void substituteProperty(PropertySubstitute substitute) {
    if (Collections.EMPTY_MAP == properties) {
      properties = new LinkedHashMap<String, PropertySubstitute>();
    }
    substitute.setTargetType(type);
    properties.put(substitute.getName(), substitute);
  }

  public void setPropertyUtils(PropertyUtils propertyUtils) {
    this.propertyUtils = propertyUtils;
  }

  /* begin: Representer */
  public void setIncludes(String... propNames) {
    this.includes = (propNames != null && propNames.length > 0) ? propNames : null;
  }

  public void setExcludes(String... propNames) {
    if (propNames != null && propNames.length > 0) {
      excludes = new HashSet<String>();
      Collections.addAll(excludes, propNames);
    } else {
      excludes = Collections.emptySet();
    }
  }

  public Set<Property> getProperties() {
    if (dumpProperties != null) {
      return dumpProperties;
    }

    if (propertyUtils != null) {
      if (includes != null) {
        dumpProperties = new LinkedHashSet<Property>();
        for (String propertyName : includes) {
          if (!excludes.contains(propertyName)) {
            dumpProperties.add(getProperty(propertyName));
          }
        }
        return dumpProperties;
      }

      final Set<Property> readableProps = (beanAccess == null) ? propertyUtils.getProperties(type)
          : propertyUtils.getProperties(type, beanAccess);

      if (properties.isEmpty()) {
        if (excludes.isEmpty()) {
          return dumpProperties = readableProps;
        }
        dumpProperties = new LinkedHashSet<Property>();
        for (Property property : readableProps) {
          if (!excludes.contains(property.getName())) {
            dumpProperties.add(property);
          }
        }
        return dumpProperties;
      }

      if (!delegatesChecked) {
        checkDelegates();
      }

      dumpProperties = new LinkedHashSet<Property>();

      for (Property property : properties.values()) {
        if (!excludes.contains(property.getName()) && property.isReadable()) {
          dumpProperties.add(property);
        }
      }

      for (Property property : readableProps) {
        if (!excludes.contains(property.getName())) {
          dumpProperties.add(property);
        }
      }

      return dumpProperties;
    }
    return null;
  }

  /* end: Representer */

  /*------------ Maybe something useful to override :) ---------*/

  public boolean setupPropertyType(String key, Node valueNode) {
    return false;
  }

  public boolean setProperty(Object targetBean, String propertyName, Object value)
      throws Exception {
    return false;
  }

  /**
   * This method should be overridden for TypeDescription implementations that are supposed to
   * implement instantiation logic that is different from default one as implemented in YAML
   * constructors. Note that even if you override this method, default filling of fields with
   * variables from parsed YAML will still occur later.
   *
   * @param node - node to construct the instance from
   * @return new instance
   */
  public Object newInstance(Node node) {
    if (impl != null) {
      try {
        java.lang.reflect.Constructor<?> c = impl.getDeclaredConstructor();
        c.setAccessible(true);
        return c.newInstance();
      } catch (Exception e) {
        log.fine(e.getLocalizedMessage());
        impl = null;
      }
    }
    return null;
  }

  public Object newInstance(String propertyName, Node node) {
    return null;
  }

  /**
   * Is invoked after entity is filled with values from deserialized YAML
   *
   * @param obj - deserialized entity
   * @return postprocessed deserialized entity
   */
  public Object finalizeConstruction(Object obj) {
    return obj;
  }

}