io.github.johnjcool.keycloak.broker.cas.jaxb.AttributesWrapper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of keycloak-cas-services Show documentation
Show all versions of keycloak-cas-services Show documentation
Extend Keycloack with CAS IDP.
package io.github.johnjcool.keycloak.broker.cas.jaxb;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlType;
import org.w3c.dom.Element;
@XmlType
public class AttributesWrapper {
private final List> attributes = new ArrayList<>();
@XmlAnyElement
public List> getAttributes() {
return attributes;
}
/**
*
* To Read-Only Map
*
*
* @return
*/
public Map toMap() {
// Note: Due to type erasure, you cannot use properties.stream() directly when unmashalling is used..
List> attrs = attributes;
return attrs.stream().collect(Collectors.toMap(AttributesWrapper::extractLocalName, AttributesWrapper::extractTextContent));
}
/**
*
* Extract local name from obj
, whether it's javax.xml.bind.JAXBElement or org.w3c.dom.Element;
*
*
* @param obj
* @return
*/
@SuppressWarnings("unchecked")
private static String extractLocalName(final Object obj) {
Map, Function super Object, String>> strFuncs = new HashMap<>();
strFuncs.put(JAXBElement.class, (jaxb) -> ((JAXBElement) jaxb).getName().getLocalPart());
strFuncs.put(Element.class, ele -> ((Element) ele).getLocalName());
return extractPart(obj, strFuncs).orElse("");
}
/**
*
* Extract text content from obj
, whether it's javax.xml.bind.JAXBElement or org.w3c.dom.Element;
*
*
* @param obj
* @return
*/
@SuppressWarnings("unchecked")
private static String extractTextContent(final Object obj) {
Map, Function super Object, String>> strFuncs = new HashMap<>();
strFuncs.put(JAXBElement.class, (jaxb) -> ((JAXBElement) jaxb).getValue());
strFuncs.put(Element.class, ele -> ((Element) ele).getTextContent());
return extractPart(obj, strFuncs).orElse("");
}
/**
* Check class type of obj
according to types listed in strFuncs
keys, then extract some string part from it according
* to the extract function specified in strFuncs
values.
*
* @param obj
* @param strFuncs
* @return
*/
private static Optional extractPart(final ObjType obj, final Map, Function super ObjType, T>> strFuncs) {
for (Class> clazz : strFuncs.keySet()) {
if (clazz.isInstance(obj)) {
return Optional.of(strFuncs.get(clazz).apply(obj));
}
}
return Optional.empty();
}
}