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