1 package cz.cuni.amis.pogamut.udk.communication.translator.itemdescriptor;
2
3 import java.lang.reflect.Field;
4 import java.util.HashMap;
5 import java.util.List;
6 import java.util.Map;
7
8 import cz.cuni.amis.pogamut.udk.communication.messages.ItemType;
9 import cz.cuni.amis.utils.ClassUtils;
10
11
12
13
14
15
16
17
18 public class ItemDescriptor {
19
20 @ItemDescriptorField
21 private int amount;
22 @ItemDescriptorField
23 private String inventoryType;
24 @ItemDescriptorField
25 private ItemType pickupType;
26 @ItemDescriptorField
27 private ItemType.Category itemCategory;
28
29 public int getAmount() {
30 return amount;
31 }
32
33 public String getInventoryType() {
34 return inventoryType;
35 }
36
37 public ItemType getPickupType() {
38 return pickupType;
39 }
40
41 public ItemType.Category getItemCategory() {
42 return itemCategory;
43 }
44
45
46
47
48
49
50
51
52 protected String fieldToName(String string) {
53 String result = string.substring(string.lastIndexOf(".") + 1);
54 return firstCharToUpperCase(result);
55 }
56
57 protected String firstCharToUpperCase(String input) {
58 return input.substring(0, 1).toUpperCase() + input.substring(1);
59 }
60
61
62
63
64
65
66
67
68 protected void doReflexion(Object configMsg, Class<? extends ItemDescriptor> clazz) {
69 Field[] configMsgFields = configMsg.getClass().getDeclaredFields();
70 Map<String, Field> configMsgFieldsMap = new HashMap<String, Field>();
71 for (Field field : configMsgFields) {
72 configMsgFieldsMap.put(field.getName(), field);
73 }
74 List<Field> descFields = ClassUtils.getAllFields(clazz, false);
75 for (Field descField : descFields) {
76 if (!descField.isAnnotationPresent(ItemDescriptorField.class)) {
77 continue;
78 }
79 descField.setAccessible(true);
80 String key = fieldToName(descField.toString());
81 Field configField = configMsgFieldsMap.get(key);
82 try {
83 if (configField == null) {
84 descField.set(this, null);
85 } else {
86 configField.setAccessible(true);
87 descField.set(this, configField.get(configMsg));
88 configField.setAccessible(false);
89 }
90 } catch (IllegalArgumentException e) {
91 e.printStackTrace();
92 } catch (IllegalAccessException e) {
93 e.printStackTrace();
94 } finally {
95 descField.setAccessible(false);
96 }
97 }
98 }
99
100 @Override
101 public String toString() {
102 return new String("ITEM DESCRIPTOR for PickupType: " + pickupType + ", Inv.Type: " + inventoryType
103 + ", Amount: " + amount + ", category: " + itemCategory.toString());
104 }
105 }