1 package fr.in2p3.jsaga.helpers;
2
3 import fr.in2p3.jsaga.impl.monitoring.MetricType;
4 import org.ogf.saga.error.DoesNotExistException;
5 import org.ogf.saga.error.NotImplementedException;
6
7 import java.text.ParseException;
8 import java.text.SimpleDateFormat;
9 import java.util.Date;
10
11
12
13
14
15
16
17
18
19
20
21
22
23 public class AttributeSerializer<E> {
24 private MetricType m_type;
25
26 public AttributeSerializer(MetricType type) {
27 m_type = type;
28 }
29
30 public E fromString(String value) throws NotImplementedException, DoesNotExistException {
31 if (value!=null && !value.equals("")) {
32 switch(m_type) {
33 case String:
34 return (E) value;
35 case Int:
36 return (E) Integer.valueOf(value);
37 case Enum:
38 throw new NotImplementedException("Metrics with type Enum must override method fromString");
39 case Float:
40 return (E) Float.valueOf(value);
41 case Bool:
42 return (E) Boolean.valueOf(value);
43 case Time:
44 try {
45 return (E) new SimpleDateFormat().parse(value);
46 } catch (ParseException e) {
47 throw new RuntimeException();
48 }
49 case Trigger:
50 throw new DoesNotExistException("Metrics with type Trigger have no value");
51 default:
52 throw new NotImplementedException("Metrics with unknown type must override method fromString");
53 }
54 } else {
55 return null;
56 }
57 }
58
59 public String toString(E value) throws DoesNotExistException {
60 if (value != null) {
61 switch(m_type) {
62 case String:
63 return (String) value;
64 case Int:
65 return value.toString();
66 case Enum:
67 return ((Enum) value).name();
68 case Float:
69 return value.toString();
70 case Bool:
71 return ((Boolean) value).booleanValue() ? "True" : "False";
72 case Time:
73 return new SimpleDateFormat().format((Date) value);
74 case Trigger:
75 throw new DoesNotExistException("Metrics of type Trigger have no value");
76 default:
77 return value.toString();
78 }
79 } else {
80 return null;
81 }
82 }
83
84 public E fromStringArray(String[] values) throws NotImplementedException, DoesNotExistException {
85 if (values!=null && values.length>0) {
86 return this.fromString(values[0]);
87 } else {
88 return null;
89 }
90 }
91
92 public String[] toStringArray(E value) throws DoesNotExistException {
93 if (value != null) {
94 return new String[]{this.toString(value)};
95 } else {
96 return new String[0];
97 }
98 }
99 }