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

Matthias Piepkorn
2017-01-29 37a97a22fd9882543dbe8cc524c42af4dc9f14d1
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;
8 import org.keycloak.protocol.cas.representations.CasServiceResponse;
9
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
26     public static String marshalXml(CasServiceResponse serviceResponse) {
27         try {
28             JAXBContext jaxbContext = JAXBContext.newInstance(CasServiceResponse.class);
29             Marshaller marshaller = jaxbContext.createMarshaller();
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
42     public static String marshalJson(CasServiceResponse serviceResponse) {
43         ObjectMapper mapper = new ObjectMapper();
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 }