Project

General

Profile

1
package eu.dnetlib.enabling.annotations;
2

    
3
import com.google.gson.Gson;
4

    
5
import eu.dnetlib.rmi.objects.is.DnetResourceType;
6
import eu.dnetlib.rmi.soap.exceptions.InformationServiceException;
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
			default:
42
				throw new InformationServiceException("Invalid format " + a.format());
43
			}
44
		} else {
45
			throw new InformationServiceException("Object of " + o.getClass() + " is not a DnetResource (missing annotation)");
46
		}
47
	}
48

    
49
	public static final <T> T convertToObject(final String s, final Class<T> clazz) throws InformationServiceException {
50
		if (isDnetResource(clazz)) {
51
			final DnetResource a = clazz.getAnnotation(DnetResource.class);
52
			switch (a.format()) {
53
			case JSON:
54
				return new Gson().fromJson(s, clazz);
55
			case XML:
56
				throw new InformationServiceException("NOT IMPLEMENTED");
57
			case TEXT:
58
				try {
59
					return clazz.getConstructor(String.class).newInstance(s);
60
				} catch (Throwable e) {
61
					throw new InformationServiceException("Cannot instantiate object of Class " + clazz);
62
				}
63
			default:
64
				throw new InformationServiceException("Invalid format " + a.format());
65
			}
66
		} else {
67
			throw new InformationServiceException("Class" + clazz + " is not a DnetResource (missing annotation)");
68
		}
69
	}
70
}
(3-3/5)