|
| 1 | +package io.adminshell.aas.v3.dataformat.jsonld; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.annotation.JsonProperty; |
| 4 | +import com.fasterxml.jackson.annotation.JsonTypeName; |
| 5 | +import com.fasterxml.jackson.core.JsonGenerator; |
| 6 | +import com.fasterxml.jackson.core.JsonToken; |
| 7 | +import com.fasterxml.jackson.core.type.WritableTypeId; |
| 8 | +import com.fasterxml.jackson.databind.SerializerProvider; |
| 9 | +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; |
| 10 | +import com.fasterxml.jackson.databind.ser.BeanSerializer; |
| 11 | +import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; |
| 12 | + |
| 13 | +import org.slf4j.Logger; |
| 14 | +import org.slf4j.LoggerFactory; |
| 15 | + |
| 16 | +import java.io.IOException; |
| 17 | +import java.lang.reflect.Field; |
| 18 | +import java.math.BigInteger; |
| 19 | +import java.util.*; |
| 20 | +import java.util.stream.Stream; |
| 21 | + |
| 22 | + |
| 23 | +public class JsonLDSerializer extends BeanSerializer { |
| 24 | + |
| 25 | + private final Logger logger = LoggerFactory.getLogger(JsonLDSerializer.class); |
| 26 | + |
| 27 | + private static int currentRecursionDepth = 0; |
| 28 | + |
| 29 | + static final Map<String, String> contextItems; |
| 30 | + |
| 31 | + static { |
| 32 | + contextItems = new HashMap<>(); |
| 33 | + contextItems.put("ids", "https://w3id.org/idsa/core/"); |
| 34 | + contextItems.put("idsc", "https://w3id.org/idsa/code/"); |
| 35 | + contextItems.put("xsd", "http://www.w3.org/2001/XMLSchema#"); |
| 36 | + contextItems.put("owl", "http://www.w3.org/2002/07/owl#"); |
| 37 | + contextItems.put("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); |
| 38 | + contextItems.put("aas", "https://admin-shell.io/aas/3/0/RC01/"); |
| 39 | + contextItems.put("iec61360", "https://admin-shell.io/DataSpecificationTemplates/DataSpecificationIEC61360/3/0/RC01/"); |
| 40 | + contextItems.put("phys_unit", "https://admin-shell.io/DataSpecificationTemplates/DataSpecificationPhysicalUnit/3/0/RC01/"); |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | + JsonLDSerializer(BeanSerializerBase src) { |
| 45 | + super(src); |
| 46 | + } |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | + @Override |
| 51 | + public void serializeWithType(Object bean, JsonGenerator gen, SerializerProvider provider, TypeSerializer typeSer) throws IOException { |
| 52 | + gen.setCurrentValue(bean); |
| 53 | + |
| 54 | + currentRecursionDepth++; |
| 55 | + gen.writeStartObject(); |
| 56 | + |
| 57 | + if (currentRecursionDepth == 1) { |
| 58 | + Map<String, String> filteredContext = new HashMap<>(); |
| 59 | + filterContextWrtBean(bean, filteredContext); |
| 60 | + gen.writeObjectField("@context", filteredContext); |
| 61 | + //gen.writeStringField("@context", "https://jira.iais.fraunhofer.de/stash/projects/ICTSL/repos/ids-infomodel-commons/raw/jsonld-context/3.0.0/context.jsonld"); // only add @context on top level |
| 62 | + |
| 63 | + } |
| 64 | + WritableTypeId typeIdDef = _typeIdDef(typeSer, bean, JsonToken.START_OBJECT); |
| 65 | + String resolvedTypeId = typeIdDef.id != null ? typeIdDef.id.toString() : typeSer.getTypeIdResolver().idFromValue(bean); |
| 66 | + if (resolvedTypeId != null) { |
| 67 | + gen.writeStringField(typeIdDef.asProperty, resolvedTypeId); |
| 68 | + } |
| 69 | + if (_propertyFilterId != null) { |
| 70 | + serializeFieldsFiltered(bean, gen, provider); |
| 71 | + } else { |
| 72 | + serializeFields(bean, gen, provider); |
| 73 | + } |
| 74 | + gen.writeEndObject(); |
| 75 | + currentRecursionDepth--; |
| 76 | + } |
| 77 | + |
| 78 | + |
| 79 | + private void filterContextWrtBean(Object bean, Map<String, String> filteredContext) { |
| 80 | + //Some default entries for AAS |
| 81 | + filteredContext.put("aas", "https://admin-shell.io/aas/3/0/RC01/"); |
| 82 | + filteredContext.put("iec61360", "https://admin-shell.io/DataSpecificationTemplates/DataSpecificationIEC61360/3/0/RC01/"); |
| 83 | + filteredContext.put("phys_unit", "https://admin-shell.io/DataSpecificationTemplates/DataSpecificationPhysicalUnit/3/0/RC01/"); |
| 84 | + |
| 85 | + if(bean == null || bean.getClass().getName().equals("com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl") || bean.getClass().getName().equals("org.apache.jena.ext.xerces.jaxp.datatype.XMLGregorianCalendarImpl") || bean.getClass() == BigInteger.class) return; // XMLGregorianCalendarImpl causes infinite recursion |
| 86 | + |
| 87 | + //Check if RdfResource or TypedLiteral is used. They contain a field called "type" which can reference to any namespace |
| 88 | + //Therefore it is vital to also check the value of the type field for prefixes that need to be included in the context |
| 89 | + if(bean.getClass().getSimpleName().equals("LangString")) |
| 90 | + { |
| 91 | + //LangString is of type rdf:langString, so this must be present |
| 92 | + filteredContext.put("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); |
| 93 | + } |
| 94 | + contextItems.forEach((p, u) -> { |
| 95 | + JsonTypeName typeNameAnnotation = bean.getClass().getAnnotation(JsonTypeName.class); |
| 96 | + if(typeNameAnnotation != null && typeNameAnnotation.value().contains(p)) { |
| 97 | + filteredContext.put(p, u); |
| 98 | + } |
| 99 | + Stream.of(bean.getClass().getMethods()).forEach(m -> { |
| 100 | + JsonProperty propertyAnnotation = m.getAnnotation(JsonProperty.class); |
| 101 | + if(propertyAnnotation != null && propertyAnnotation.value().contains(p)) { |
| 102 | + filteredContext.put(p, u); |
| 103 | + } |
| 104 | + }); |
| 105 | + }); |
| 106 | + Stream.of(bean.getClass().getMethods()).forEach(m -> { |
| 107 | + // run though all properties and check annotations. These annotations should contain the prefixes |
| 108 | + JsonProperty prop = m.getAnnotation(JsonProperty.class); |
| 109 | + if(prop != null) |
| 110 | + { |
| 111 | + for(Map.Entry<String, String> entry : contextItems.entrySet()) |
| 112 | + { |
| 113 | + if(prop.value().startsWith(entry.getKey())) |
| 114 | + { |
| 115 | + filteredContext.put(entry.getKey(), entry.getValue()); |
| 116 | + break; |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + }); |
| 121 | + // run through fields recursively |
| 122 | + for(Field f : getAllFields(new HashSet<>(), bean.getClass())) { |
| 123 | + |
| 124 | + if(Collection.class.isAssignableFrom(f.getType())) |
| 125 | + { |
| 126 | + try { |
| 127 | + if(f.getType().getName().startsWith("java.") && !f.getType().getName().startsWith("java.util")) continue; |
| 128 | + boolean accessible = f.isAccessible(); |
| 129 | + f.setAccessible(true); |
| 130 | + Collection<?> c = (Collection<?>) f.get(bean); |
| 131 | + if(c == null) { |
| 132 | + continue; |
| 133 | + } |
| 134 | + for(Object o : c) |
| 135 | + { |
| 136 | + filterContextWrtBean(o, filteredContext); |
| 137 | + } |
| 138 | + f.setAccessible(accessible); |
| 139 | + } |
| 140 | + catch (IllegalAccessException e) { |
| 141 | + e.printStackTrace(); |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + if (f.getType().isPrimitive() || f.getType().isEnum() || f.getType().isArray() |
| 146 | + || f.getType().getName().contains("java.") |
| 147 | + || f.getType().getName().contains("javax.")) continue; |
| 148 | + |
| 149 | + try { |
| 150 | + boolean wasAccessible = f.isAccessible(); |
| 151 | + f.setAccessible(true); |
| 152 | + filterContextWrtBean(f.get(bean), filteredContext); |
| 153 | + f.setAccessible(wasAccessible); |
| 154 | + } catch (IllegalAccessException ignored) { |
| 155 | + //logger.error("setting accessible failed"); //We can catch that here, as IllegalReflectiveAccess cannot occur on our own packages |
| 156 | + } |
| 157 | + |
| 158 | + //f.trySetAccessible(wasAccessible); |
| 159 | + |
| 160 | + } |
| 161 | + |
| 162 | + } |
| 163 | + |
| 164 | + /** |
| 165 | + * This function retrieves a set of all available fields of a class, including inherited fields |
| 166 | + * @param fields Set to which discovered fields will be added. An empty HashSet should do the trick |
| 167 | + * @param type The class for which fields should be discovered |
| 168 | + * @return set of all available fields |
| 169 | + */ |
| 170 | + private static Set<Field> getAllFields(Set<Field> fields, Class<?> type) { |
| 171 | + fields.addAll(Arrays.asList(type.getDeclaredFields())); |
| 172 | + |
| 173 | + if (type.getSuperclass() != null) { |
| 174 | + getAllFields(fields, type.getSuperclass()); |
| 175 | + } |
| 176 | + |
| 177 | + return fields; |
| 178 | + } |
| 179 | +} |
0 commit comments