br.com.anteros.nextcloud.api.utils.XMLAnswerParser Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of Anteros-NextCloud Show documentation
Show all versions of Anteros-NextCloud Show documentation
Anteros NextCloud for Java.
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;
}
}