summaryrefslogtreecommitdiff
path: root/src/main/java/com/stileeducation/markr/converter/XmlMarkrMessageConverter.java
blob: bc84b728e8f67188aef5ca7760cfce5e701df034 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.stileeducation.markr.converter;

import com.stileeducation.markr.dto.MCQTestResultsDTO;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.xml.AbstractXmlHttpMessageConverter;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import java.util.Collections;
import java.util.List;

/**
 * Custom Message Converter for handling the text/xml+mark content type
 */
public class XmlMarkrMessageConverter extends AbstractXmlHttpMessageConverter<MCQTestResultsDTO> {

    public static final MediaType MEDIA_TYPE = new MediaType("text", "xml+markr");

    @Override
    protected MCQTestResultsDTO readFromSource(Class<? extends MCQTestResultsDTO> clazz, HttpHeaders headers, Source source) throws Exception {
        JAXBContext jaxbContext = JAXBContext.newInstance(MCQTestResultsDTO.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        return (MCQTestResultsDTO) unmarshaller.unmarshal(source);
    }

    @Override
    protected void writeToResult(MCQTestResultsDTO testResultsDTO, HttpHeaders headers, Result result) throws Exception {
        JAXBContext jaxbContext = JAXBContext.newInstance(MCQTestResultsDTO.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.marshal(testResultsDTO, result);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return MCQTestResultsDTO.class.isAssignableFrom(clazz);
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return Collections.singletonList(MEDIA_TYPE);
    }
}