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

Phy
2020-02-28 8379a316bc051ff05ac2fb06671871ab82f01feb
commit | author | age
513246 1 package org.keycloak.protocol.cas.utils;
MP 2
3 import com.fasterxml.jackson.annotation.JsonInclude;
4 import com.fasterxml.jackson.core.JsonProcessingException;
5 import com.fasterxml.jackson.core.util.DefaultIndenter;
6 import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
7 import com.fasterxml.jackson.databind.ObjectMapper;
8a5518 8 import org.keycloak.protocol.cas.representations.CASServiceResponse;
513246 9
MP 10 import javax.xml.bind.JAXBContext;
11 import javax.xml.bind.JAXBException;
12 import javax.xml.bind.Marshaller;
13 import java.io.StringWriter;
14 import java.nio.charset.StandardCharsets;
15 import java.util.HashMap;
16 import java.util.Map;
17
18 /**
19  * Helper methods to marshal service response object to XML/JSON<br
20  * For details on expected format see CAS-Protocol-Specification.html, section 2.5/2.6
21  */
22 public final class ServiceResponseMarshaller {
23     private ServiceResponseMarshaller() {
24     }
25
8a5518 26     public static String marshalXml(CASServiceResponse serviceResponse) {
513246 27         try {
8a5518 28             JAXBContext jaxbContext = JAXBContext.newInstance(CASServiceResponse.class);
513246 29             Marshaller marshaller = jaxbContext.createMarshaller();
MP 30             //disable xml header
31             marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
32             marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
33             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
34             StringWriter writer = new StringWriter();
35             marshaller.marshal(serviceResponse, writer);
36             return writer.toString();
37         } catch (JAXBException e) {
38             throw new RuntimeException(e);
39         }
40     }
41
8a5518 42     public static String marshalJson(CASServiceResponse serviceResponse) {
513246 43         ObjectMapper mapper = new ObjectMapper();
MP 44         mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
45         //Force newlines to be LF (default is system dependent)
46         DefaultPrettyPrinter printer = new DefaultPrettyPrinter()
47                 .withObjectIndenter(new DefaultIndenter("  ", "\n"));
48
49         //create wrapper node
50         Map<String, Object> casModel = new HashMap<>();
51         casModel.put("serviceResponse", serviceResponse);
52         try {
53             return mapper.writer(printer).writeValueAsString(casModel);
54         } catch (JsonProcessingException e) {
55             throw new RuntimeException(e);
56         }
57     }
58 }