1
|
package eu.dnetlib.dhp.common.utils;
|
2
|
|
3
|
import java.lang.reflect.Field;
|
4
|
|
5
|
import org.apache.avro.Schema;
|
6
|
|
7
|
/**
|
8
|
*
|
9
|
* @author Mateusz Kobos
|
10
|
*
|
11
|
*/
|
12
|
public final class AvroUtils {
|
13
|
|
14
|
public final static String primitiveTypePrefix = "org.apache.avro.Schema.Type.";
|
15
|
|
16
|
|
17
|
//------------------------ CONSTRUCTORS -------------------
|
18
|
|
19
|
|
20
|
private AvroUtils() {}
|
21
|
|
22
|
|
23
|
//------------------------ LOGIC --------------------------
|
24
|
|
25
|
|
26
|
/**
|
27
|
* For a given name of a class generated from Avro schema return
|
28
|
* a JSON schema.
|
29
|
*
|
30
|
* Apart from a name of a class you can also give a name of one of enums
|
31
|
* defined in {@link org.apache.avro.Schema.Type}; in such case an
|
32
|
* appropriate primitive type will be returned.
|
33
|
*
|
34
|
* @param typeName fully qualified name of a class generated from Avro schema,
|
35
|
* e.g. {@code eu.dnetlib.dhp.common.avro.Person},
|
36
|
* or a fully qualified name of enum defined by
|
37
|
* {@link org.apache.avro.Schema.Type},
|
38
|
* e.g. {@link org.apache.avro.Schema.Type.STRING}.
|
39
|
* @return JSON string
|
40
|
*/
|
41
|
public static Schema toSchema(String typeName) {
|
42
|
Schema schema = null;
|
43
|
if(typeName.startsWith(primitiveTypePrefix)){
|
44
|
String shortName = typeName.substring(
|
45
|
primitiveTypePrefix.length(), typeName.length());
|
46
|
schema = getPrimitiveTypeSchema(shortName);
|
47
|
} else {
|
48
|
schema = getAvroClassSchema(typeName);
|
49
|
}
|
50
|
return schema;
|
51
|
}
|
52
|
|
53
|
private static Schema getPrimitiveTypeSchema(String shortName){
|
54
|
Schema.Type type = Schema.Type.valueOf(shortName);
|
55
|
return Schema.create(type);
|
56
|
}
|
57
|
|
58
|
private static Schema getAvroClassSchema(String className){
|
59
|
try {
|
60
|
Class<?> avroClass = Class.forName(className);
|
61
|
Field f = avroClass.getDeclaredField("SCHEMA$");
|
62
|
return (Schema) f.get(null);
|
63
|
} catch (ClassNotFoundException e) {
|
64
|
throw new RuntimeException(
|
65
|
"Class \""+className+"\" does not exist", e);
|
66
|
} catch (SecurityException e) {
|
67
|
throw new RuntimeException(e);
|
68
|
} catch (NoSuchFieldException e) {
|
69
|
throw new RuntimeException(e);
|
70
|
} catch (IllegalArgumentException e) {
|
71
|
throw new RuntimeException(e);
|
72
|
} catch (IllegalAccessException e) {
|
73
|
throw new RuntimeException(e);
|
74
|
}
|
75
|
}
|
76
|
|
77
|
}
|