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

io.descoped.dc.api.services.InjectionParameters Maven / Gradle / Ivy

There is a newer version: 2.0.4
Show newest version
package io.descoped.dc.api.services;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

public class InjectionParameters implements Services {

    private final Map, AtomicReference> instanceMap = new ConcurrentHashMap<>();

    public InjectionParameters() {
    }

    @Override
    public  boolean contains(Class clazz) {
        return instanceMap.containsKey(clazz);
    }

    @Override
    public  R get(Class clazz) {
        try {
            return (R) instanceMap.get(clazz).get();
        } catch (NullPointerException npe) {
            return null;
        }
    }

    @Override
    public Map, Object> asMap() {
        return instanceMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, value -> value.getValue().get()));
    }

    @Override
    public  Services register(Class clazz, Object instance) {
        instanceMap.put(clazz, new AtomicReference<>(instance));
        return this;
    }

    public void putAll(InjectionParameters injectionParameters) {
        for (Map.Entry, AtomicReference> entry : injectionParameters.instanceMap.entrySet()) {
            instanceMap.put(entry.getKey(), entry.getValue());
        }
    }

}