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

org.aarboard.nextcloud.api.utils.JsonAnswerParser Maven / Gradle / Ivy

The newest version!
package org.aarboard.nextcloud.api.utils;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import org.aarboard.nextcloud.api.exception.NextcloudApiException;

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

public class JsonAnswerParser implements ConnectorCommon.ResponseParser {

    private static final Map> PARSERS = new HashMap<>();

    private final ObjectReader objectReader;

    private JsonAnswerParser(Class answerClass) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

        objectReader = objectMapper.readerFor(answerClass);
    }

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

    @Override
    public A parseResponse(Reader reader) {
        try (Reader response = reader) {
            return objectReader.readValue(response);
        } catch (IOException e) {
            throw new NextcloudApiException(e);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy