mirror of https://github.com/jacekkow/keycloak-protocol-cas

Jacek Kowalski
2023-07-12 fdb9f6bf5fc43d54c9396dc4dd577b6c84ecdb9d
commit | author | age
513246 1 package org.keycloak.protocol.cas.utils;
MP 2
fdb9f6 3 import jakarta.xml.bind.JAXBElement;
JK 4 import jakarta.xml.bind.annotation.XmlAccessType;
5 import jakarta.xml.bind.annotation.XmlAccessorType;
6 import jakarta.xml.bind.annotation.XmlAnyElement;
7 import jakarta.xml.bind.annotation.XmlSchema;
8 import jakarta.xml.bind.annotation.adapters.XmlAdapter;
8a5518 9 import org.keycloak.protocol.cas.representations.CASServiceResponse;
513246 10
MP 11 import javax.xml.namespace.QName;
12 import java.util.ArrayList;
0ad1a9 13 import java.util.Collection;
513246 14 import java.util.List;
MP 15 import java.util.Map;
16
17 /**
18  * Transforms the attribute map of the AuthenticationSuccess object (which can contain either simple values or
19  * lists) to a flat list of XML nodes, where the key is the node name.<br>
20  * Lists output multiple XML nodes with the same name.
21  */
22 public final class AttributesMapAdapter extends XmlAdapter<AttributesMapAdapter.AttributeWrapperType, Map<String, Object>> {
23     @Override
24     public AttributeWrapperType marshal(Map<String, Object> v) throws Exception {
25         return new AttributeWrapperType(v);
26     }
27
28     @Override
29     public Map<String, Object> unmarshal(AttributeWrapperType v) throws Exception {
30         throw new IllegalStateException("not implemented");
31     }
32
33     @XmlAccessorType(XmlAccessType.FIELD)
34     static class AttributeWrapperType {
35         @XmlAnyElement
36         private final List<JAXBElement<String>> elements;
37
38         AttributeWrapperType(Map<String, Object> attributes) {
39             this.elements = new ArrayList<>();
40             for (Map.Entry<String, Object> entry : attributes.entrySet()) {
0ad1a9 41                 if (entry.getValue() instanceof Collection) {
MP 42                     for (Object item : ((Collection) entry.getValue())) {
513246 43                         addElement(entry.getKey(), item);
MP 44                     }
45                 } else {
46                     addElement(entry.getKey(), entry.getValue());
47                 }
48             }
49         }
50
51         private void addElement(String name, Object value) {
52             if (value != null) {
8a5518 53                 String namespace = CASServiceResponse.class.getPackage().getAnnotation(XmlSchema.class).namespace();
513246 54                 elements.add(new JAXBElement<>(new QName(namespace, name), String.class, value.toString()));
MP 55             }
56         }
57     }
58 }