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

com.syntaxphoenix.syntaxapi.data.DataAdapterRegistry Maven / Gradle / Ivy

The newest version!
package com.syntaxphoenix.syntaxapi.data;

import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

import com.syntaxphoenix.syntaxapi.utils.java.Primitives;

public abstract class DataAdapterRegistry {

    private final ConcurrentHashMap, DataAdapter> adapters = new ConcurrentHashMap<>();

    protected abstract  DataAdapter buildAdapter(Class clazz);

    protected abstract  DataAdapter createAdapter(Class primitiveType, Class resultType,
        Function builder, Function extractor);

    public  B wrap(Class type, T value) {
        DataAdapter adapter = adapters.computeIfAbsent(Primitives.fromPrimitive(type), (clazz) -> buildAdapter(clazz));
        return adapter == null ? null : adapter.build(value);
    }

    public  T extract(Class type, B base) throws ClassCastException, IllegalArgumentException {
        type = Primitives.fromPrimitive(type);
        DataAdapter adapter = this.adapters.computeIfAbsent(type, (clazz) -> buildAdapter(clazz));
        if (adapter == null || !adapter.isInstance(base)) {
            return null;
        }
        Object foundValue = adapter.extract(base);
        return type.isInstance(foundValue) ? type.cast(foundValue) : null;
    }

    public  boolean isInstanceOf(Class type, B base) {
        DataAdapter adapter = adapters.computeIfAbsent(Primitives.fromPrimitive(type), (clazz) -> buildAdapter(clazz));
        return adapter == null ? null : adapter.isInstance(base);
    }

    public boolean hasAdapter(Class type) {
        return adapters.containsKey(Primitives.fromPrimitive(type));
    }

}