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

org.zodiac.fastorm.rdb.codec.ClobValueCodec Maven / Gradle / Ivy

The newest version!
package org.zodiac.fastorm.rdb.codec;

import io.netty.buffer.ByteBuf;

import org.zodiac.fastorm.core.ValueCodec;
import org.zodiac.fastorm.rdb.utils.FeatureUtils;
import org.zodiac.sdk.toolkit.util.ExceptionUtil;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.sql.Clob;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class ClobValueCodec implements ValueCodec {

    public static final ClobValueCodec INSTANCE = new ClobValueCodec();

    public ClobValueCodec() {
        super();
    }

    @Override
    public Object encode(Object value) {
        try {
            if (value instanceof Clob) {
                return value;
            }
            if (value instanceof String) {
                return value;
            }

            if (value instanceof ByteBuffer) {
                return value;
            }

            if (value instanceof ByteBuf) {
                return ((ByteBuf) value).nioBuffer();
            }
        } catch (Exception e) {
            ExceptionUtil.chuck(e);
        }
        return value.toString();
    }

    @Override
    public Object decode(Object data) {
        try {
            if (data instanceof ByteBuffer) {
                ByteBuffer byteBuffer = ((ByteBuffer) data);
                return StandardCharsets.UTF_8.decode(byteBuffer).toString();
            }
            if (data instanceof Clob) {
                Clob clobData = ((Clob) data);
                return clobData.getSubString(1, (int) clobData.length());
            }
            if (FeatureUtils.r2dbcIsAlive()) {
                Mono mono = null;
                if (data instanceof io.r2dbc.spi.Clob) {
                    mono = Flux.from(((io.r2dbc.spi.Clob) data).stream())
                               .collect(Collectors.joining());
                }
                if (mono != null) {
                    /*TODO: A better way?*/
                    return mono.toFuture().get(10, TimeUnit.SECONDS);
                }
            }
        } catch (Exception e) {
            ExceptionUtil.chuck(e);
        }
        return data;
    }

    public static ClobValueCodec getInstance() {
        return ClobValueCodecHolder.INSTANCE;
    }

    private static class ClobValueCodecHolder {
        private static final ClobValueCodec INSTANCE = new ClobValueCodec();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy