1
|
package eu.dnetlib.enabling.is.annotations;
|
2
|
|
3
|
import com.google.gson.Gson;
|
4
|
|
5
|
import eu.dnetlib.enabling.is.rmi.InformationServiceException;
|
6
|
import eu.dnetlib.enabling.is.rmi.objects.DnetResourceType;
|
7
|
|
8
|
public class DnetResourceHelper {
|
9
|
|
10
|
public static boolean isDnetResource(final Class<?> clazz) {
|
11
|
return clazz.isAnnotationPresent(DnetResource.class);
|
12
|
}
|
13
|
|
14
|
public static boolean isDnetResource(final Object o) {
|
15
|
return isDnetResource(o.getClass());
|
16
|
}
|
17
|
|
18
|
public static final DnetResourceType obtainResourceType(final Class<?> clazz) throws InformationServiceException {
|
19
|
if (isDnetResource(clazz)) {
|
20
|
final DnetResource a = clazz.getAnnotation(DnetResource.class);
|
21
|
return new DnetResourceType(a.type(), a.kind(), a.format());
|
22
|
} else {
|
23
|
throw new InformationServiceException("Class " + clazz + " is not a DnetResource (missing annotation)");
|
24
|
}
|
25
|
}
|
26
|
|
27
|
public static final DnetResourceType obtainResourceType(final Object o) throws InformationServiceException {
|
28
|
return obtainResourceType(o.getClass());
|
29
|
}
|
30
|
|
31
|
public static final String convertToString(final Object o) throws InformationServiceException {
|
32
|
if (isDnetResource(o)) {
|
33
|
final DnetResource a = o.getClass().getAnnotation(DnetResource.class);
|
34
|
switch (a.format()) {
|
35
|
case JSON:
|
36
|
return new Gson().toJson(o);
|
37
|
case XML:
|
38
|
throw new InformationServiceException("NOT IMPLEMENTED");
|
39
|
case TEXT:
|
40
|
return o.toString();
|
41
|
case SERVICE:
|
42
|
throw new InformationServiceException("NOT IMPLEMENTED");
|
43
|
default:
|
44
|
throw new InformationServiceException("Invalid format " + a.format());
|
45
|
}
|
46
|
} else {
|
47
|
throw new InformationServiceException("Object of " + o.getClass() + " is not a DnetResource (missing annotation)");
|
48
|
}
|
49
|
}
|
50
|
|
51
|
public static final <T> T convertToObject(final String s, final Class<T> clazz) throws InformationServiceException {
|
52
|
if (isDnetResource(clazz)) {
|
53
|
final DnetResource a = clazz.getAnnotation(DnetResource.class);
|
54
|
switch (a.format()) {
|
55
|
case JSON:
|
56
|
return new Gson().fromJson(s, clazz);
|
57
|
case XML:
|
58
|
throw new InformationServiceException("NOT IMPLEMENTED");
|
59
|
case TEXT:
|
60
|
try {
|
61
|
return clazz.getConstructor(String.class).newInstance(s);
|
62
|
} catch (Throwable e) {
|
63
|
throw new InformationServiceException("Cannot instantiate object of Class " + clazz);
|
64
|
}
|
65
|
case SERVICE:
|
66
|
throw new InformationServiceException("NOT IMPLEMENTED");
|
67
|
default:
|
68
|
throw new InformationServiceException("Invalid format " + a.format());
|
69
|
}
|
70
|
} else {
|
71
|
throw new InformationServiceException("Class" + clazz + " is not a DnetResource (missing annotation)");
|
72
|
}
|
73
|
}
|
74
|
}
|