All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.anteros.nextcloud.api.utils.XMLAnswerParser Maven / Gradle / Ivy

There is a newer version: 1.0.16
Show newest version
package br.com.anteros.nextcloud.api.utils;

import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import br.com.anteros.nextcloud.api.exception.NextCloudApiException;
import br.com.anteros.nextcloud.api.utils.ConnectorCommon.ResponseParser;

public class XMLAnswerParser implements ResponseParser
{
    private static final Map> PARSERS = new HashMap<>();

    private final JAXBContext jAXBContext;

    public XMLAnswerParser(Class answerClass)
    {
        try {
            jAXBContext = JAXBContext.newInstance(XMLAnswer.class, answerClass);
        } catch (JAXBException e) {
            throw new NextCloudApiException(e);
        }
    }

    public static  XMLAnswerParser getInstance(Class answerClass)
    {
        @SuppressWarnings("unchecked")
        XMLAnswerParser parser = (XMLAnswerParser) PARSERS.get(answerClass.getName());
        if (parser == null)
        {
            synchronized (PARSERS)
            {
                if (parser == null)
                {
                    parser = new XMLAnswerParser<>(answerClass);
                    PARSERS.put(answerClass.getName(), parser);
                }
            }
        }
        return parser;
    }

    @Override
    public A parseResponse(Reader xmlStream)
    {
        try {
            return tryParseAnswer(xmlStream);
        } catch (Exception e) {
            throw new NextCloudApiException(e);
        } finally {
            try {
                xmlStream.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }

    @SuppressWarnings("unchecked")
    private A tryParseAnswer(Reader xmlStream) throws JAXBException, IOException
    {
        Unmarshaller unmarshaller = jAXBContext.createUnmarshaller();
        Object result = unmarshaller.unmarshal(xmlStream);
        return (A) result;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy