summaryrefslogtreecommitdiffstats
path: root/Essentials/src/net/ess3/storage/BukkitConstructor.java
blob: 068d31608f7dc3b7c509e179896fcd49cd455ecc (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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package net.ess3.storage;

import net.ess3.Essentials;
import net.ess3.api.server.IPlugin;
import net.ess3.api.server.Material;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.nodes.*;


public class BukkitConstructor extends Constructor
{
	private final transient Pattern NUMPATTERN = Pattern.compile("\\d+");
	private final transient IPlugin plugin;

	public BukkitConstructor(final Class clazz, final IPlugin plugin)
	{
		super(clazz);
		this.plugin = plugin;
		yamlClassConstructors.put(NodeId.scalar, new ConstructBukkitScalar());
		yamlClassConstructors.put(NodeId.mapping, new ConstructBukkitMapping());
	}


	private class ConstructBukkitScalar extends ConstructScalar
	{
		@Override
		public Object construct(final Node node)
		{
			if (node.getType().equals(Material.class))
			{
				final String val = (String)constructScalar((ScalarNode)node);
				Material mat;
				if (NUMPATTERN.matcher(val).matches())
				{
					final int typeId = Integer.parseInt(val);
					mat = Material.getMaterial(typeId);
				}
				else
				{
					mat = Material.matchMaterial(val);
				}
				return mat;
			}
			if (node.getType().equals(MaterialData.class))
			{
				final String val = (String)constructScalar((ScalarNode)node);
				if (val.isEmpty())
				{
					return null;
				}
				final String[] split = val.split("[:+',;.]", 2);
				if (split.length == 0)
				{
					return null;
				}
				Material mat;
				if (NUMPATTERN.matcher(split[0]).matches())
				{
					final int typeId = Integer.parseInt(split[0]);
					mat = Material.get(typeId);
				}
				else
				{
					mat = Material.match(split[0]);
				}
				if (mat == null)
				{
					return null;
				}
				byte data = 0;
				if (split.length == 2 && NUMPATTERN.matcher(split[1]).matches())
				{
					data = Byte.parseByte(split[1]);
				}
				return new MaterialData(mat, data);
			}
			if (node.getType().equals(ItemStack.class))
			{
				final String val = (String)constructScalar((ScalarNode)node);
				if (val.isEmpty())
				{
					return null;
				}
				final String[] split1 = val.split("\\W");
				if (split1.length == 0)
				{
					return null;
				}
				final String[] split2 = split1[0].split("[:+',;.]", 2);
				if (split2.length == 0)
				{
					return null;
				}
				Material mat;
				if (NUMPATTERN.matcher(split2[0]).matches())
				{
					final int typeId = Integer.parseInt(split2[0]);
					mat = Material.getMaterial(typeId);
				}
				else
				{
					mat = Material.matchMaterial(split2[0]);
				}
				if (mat == null)
				{
					return null;
				}
				short data = 0;
				if (split2.length == 2 && NUMPATTERN.matcher(split2[1]).matches())
				{
					data = Short.parseShort(split2[1]);
				}
				int size = mat.getMaxStackSize();
				if (split1.length > 1 && NUMPATTERN.matcher(split1[1]).matches())
				{
					size = Integer.parseInt(split1[1]);
				}
				final ItemStack stack = new ItemStack(mat, size, data);
				if (split1.length > 2)
				{
					for (int i = 2; i < split1.length; i++)
					{
						final String[] split3 = split1[0].split("[:+',;.]", 2);
						if (split3.length < 1)
						{
							continue;
						}
						Enchantment enchantment;
						if (NUMPATTERN.matcher(split3[0]).matches())
						{
							final int enchantId = Integer.parseInt(split3[0]);
							enchantment = Enchantment.getById(enchantId);
						}
						else
						{
							enchantment = Enchantment.getByName(split3[0].toUpperCase(Locale.ENGLISH));
						}
						if (enchantment == null)
						{
							continue;
						}
						int level = enchantment.getStartLevel();
						if (split3.length == 2 && NUMPATTERN.matcher(split3[1]).matches())
						{
							level = Integer.parseInt(split3[1]);
						}
						if (level < enchantment.getStartLevel())
						{
							level = enchantment.getStartLevel();
						}
						if (level > enchantment.getMaxLevel())
						{
							level = enchantment.getMaxLevel();
						}
						stack.addUnsafeEnchantment(enchantment, level);
					}
				}
				return stack;
			}
			if (node.getType().equals(EnchantmentLevel.class))
			{
				final String val = (String)constructScalar((ScalarNode)node);
				if (val.isEmpty())
				{
					return null;
				}
				final String[] split = val.split("[:+',;.]", 2);
				if (split.length == 0)
				{
					return null;
				}
				Enchantment enchant;
				if (NUMPATTERN.matcher(split[0]).matches())
				{
					final int typeId = Integer.parseInt(split[0]);
					enchant = Enchantment.getById(typeId);
				}
				else
				{
					enchant = Enchantment.getByName(split[0].toUpperCase(Locale.ENGLISH));
				}
				if (enchant == null)
				{
					return null;
				}
				int level = enchant.getStartLevel();
				if (split.length == 2 && NUMPATTERN.matcher(split[1]).matches())
				{
					level = Integer.parseInt(split[1]);
				}
				if (level < enchant.getStartLevel())
				{
					level = enchant.getStartLevel();
				}
				if (level > enchant.getMaxLevel())
				{
					level = enchant.getMaxLevel();
				}
				return new EnchantmentLevel(enchant, level);
			}
			if (node.getType().isEnum())
			{
				final String val = (String)constructScalar((ScalarNode)node);
				if (val.isEmpty())
				{
					return null;
				}
				for (Object object : node.getType().getEnumConstants())
				{
					if (object.toString().equalsIgnoreCase(val))
					{
						return object;
					}
				}
				return null;
			}
			return super.construct(node);
		}
	}


	private class ConstructBukkitMapping extends ConstructMapping
	{
		@Override
		public Object construct(final Node node)
		{
			if (node.getType().equals(StoredLocation.class))
			{
				//TODO: NPE checks
				final MappingNode mnode = (MappingNode)node;
				String worldName = "";
				double x = 0, y = 0, z = 0;
				float yaw = 0, pitch = 0;
				if (mnode.getValue().size() < 4)
				{
					return null;
				}
				for (NodeTuple nodeTuple : mnode.getValue())
				{
					final String key = (String)constructScalar((ScalarNode)nodeTuple.getKeyNode());
					final ScalarNode snode = (ScalarNode)nodeTuple.getValueNode();
					if (key.equalsIgnoreCase("world"))
					{
						worldName = (String)constructScalar(snode);
					}
					if (key.equalsIgnoreCase("x"))
					{
						x = Double.parseDouble((String)constructScalar(snode));
					}
					if (key.equalsIgnoreCase("y"))
					{
						y = Double.parseDouble((String)constructScalar(snode));
					}
					if (key.equalsIgnoreCase("z"))
					{
						z = Double.parseDouble((String)constructScalar(snode));
					}
					if (key.equalsIgnoreCase("yaw"))
					{
						yaw = Float.parseFloat((String)constructScalar(snode));
					}
					if (key.equalsIgnoreCase("pitch"))
					{
						pitch = Float.parseFloat((String)constructScalar(snode));
					}
				}
				if (worldName == null || worldName.isEmpty())
				{
					return null;
				}
				return new StoredLocation(worldName, x, y, z, yaw, pitch);
			}
			return super.construct(node);
		}

		@Override
		protected Object constructJavaBean2ndStep(final MappingNode node, final Object object)
		{
			Map<Class<? extends Object>, TypeDescription> typeDefinitions;
			try
			{
				final Field typeDefField = Constructor.class.getDeclaredField("typeDefinitions");
				typeDefField.setAccessible(true);
				typeDefinitions = (Map<Class<? extends Object>, TypeDescription>)typeDefField.get((Constructor)BukkitConstructor.this);
				if (typeDefinitions == null)
				{
					throw new NullPointerException();
				}
			}
			catch (Exception ex)
			{
				throw new YAMLException(ex);
			}
			flattenMapping(node);
			final Class<? extends Object> beanType = node.getType();
			final List<NodeTuple> nodeValue = node.getValue();
			for (NodeTuple tuple : nodeValue)
			{
				ScalarNode keyNode;
				if (tuple.getKeyNode() instanceof ScalarNode)
				{
					// key must be scalar
					keyNode = (ScalarNode)tuple.getKeyNode();
				}
				else
				{
					throw new YAMLException("Keys must be scalars but found: " + tuple.getKeyNode());
				}
				final Node valueNode = tuple.getValueNode();
				// keys can only be Strings
				keyNode.setType(String.class);
				final String key = (String)constructObject(keyNode);
				try
				{
					Property property;
					try
					{
						property = getProperty(beanType, key);
					}
					catch (YAMLException e)
					{
						continue;
					}
					valueNode.setType(property.getType());
					final TypeDescription memberDescription = typeDefinitions.get(beanType);
					boolean typeDetected = false;
					if (memberDescription != null)
					{
						switch (valueNode.getNodeId())
						{
						case sequence:
							final SequenceNode snode = (SequenceNode)valueNode;
							final Class<? extends Object> memberType = memberDescription.getListPropertyType(key);
							if (memberType != null)
							{
								snode.setListType(memberType);
								typeDetected = true;
							}
							else if (property.getType().isArray())
							{
								snode.setListType(property.getType().getComponentType());
								typeDetected = true;
							}
							break;
						case mapping:
							final MappingNode mnode = (MappingNode)valueNode;
							final Class<? extends Object> keyType = memberDescription.getMapKeyType(key);
							if (keyType != null)
							{
								mnode.setTypes(keyType, memberDescription.getMapValueType(key));
								typeDetected = true;
							}
							break;
						}
					}
					if (!typeDetected && valueNode.getNodeId() != NodeId.scalar)
					{
						// only if there is no explicit TypeDescription
						final Class<?>[] arguments = property.getActualTypeArguments();
						if (arguments != null)
						{
							// type safe (generic) collection may contain the
							// proper class
							if (valueNode.getNodeId() == NodeId.sequence)
							{
								final Class<?> t = arguments[0];
								final SequenceNode snode = (SequenceNode)valueNode;
								snode.setListType(t);
							}
							else if (valueNode.getTag().equals(Tag.SET))
							{
								final Class<?> t = arguments[0];
								final MappingNode mnode = (MappingNode)valueNode;
								mnode.setOnlyKeyType(t);
								mnode.setUseClassConstructor(true);
							}
							else if (property.getType().isAssignableFrom(Map.class))
							{
								final Class<?> ketType = arguments[0];
								final Class<?> valueType = arguments[1];
								final MappingNode mnode = (MappingNode)valueNode;
								mnode.setTypes(ketType, valueType);
								mnode.setUseClassConstructor(true);
							}
							else
							{
								// the type for collection entries cannot be
								// detected
							}
						}
					}
					final Object value = constructObject(valueNode);
					property.set(object, value);
				}
				catch (Exception e)
				{
					throw new YAMLException("Cannot create property=" + key + " for JavaBean="
											+ object + "; " + e.getMessage(), e);
				}
			}
			return object;
		}
	}

	@Override
	protected Class<?> getClassForNode(final Node node)
	{
		Class<?> clazz;
		final String name = node.getTag().getClassName();
		if (Essentials.testing)
		{
			clazz = super.getClassForNode(node);
		}
		else
		{
			clazz = plugin.getClassByName(name);
		}

		if (clazz == null)
		{
			throw new YAMLException("Class not found: " + name);
		}
		else
		{
			return clazz;
		}
	}
}