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

cc.youchain.protocol.Service Maven / Gradle / Ivy

There is a newer version: 1.1.5
Show newest version
package cc.youchain.protocol;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CompletableFuture;

import cc.youchain.protocol.core.Request;
import cc.youchain.protocol.core.Response;
import cc.youchain.protocol.websocket.events.Notification;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.reactivex.Flowable;

import cc.youchain.utils.Async;

/**
 * Base service implementation.
 */
public abstract class Service implements YOUChainService {

    protected final ObjectMapper objectMapper;

    public Service(boolean includeRawResponses) {
        objectMapper = ObjectMapperFactory.getObjectMapper(includeRawResponses);
    }

    protected abstract InputStream performIO(String payload) throws IOException;

    @Override
    public  T send(
            Request request, Class responseType) throws IOException {
        String payload = objectMapper.writeValueAsString(request);

        try (InputStream result = performIO(payload)) {
            if (result != null) {
                return objectMapper.readValue(result, responseType);
            } else {
                return null;
            }
        }
    }

    @Override
    public  CompletableFuture sendAsync(
            Request jsonRpc20Request, Class responseType) {
        return Async.run(() -> send(jsonRpc20Request, responseType));
    }

    @Override
    public > Flowable subscribe(
            Request request,
            String unsubscribeMethod,
            Class responseType) {
        throw new UnsupportedOperationException(
                String.format(
                        "Service %s does not support subscriptions",
                        this.getClass().getSimpleName()));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy