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

li.rudin.arduino.managed.cdi.ManagedDeviceBean Maven / Gradle / Ivy

There is a newer version: 2.12
Show newest version
package li.rudin.arduino.managed.cdi;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.enterprise.inject.spi.PassivationCapable;
import javax.enterprise.util.AnnotationLiteral;

import li.rudin.arduino.api.Arduino;
import li.rudin.arduino.api.state.ConnectionState;
import li.rudin.arduino.managed.Managed;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ManagedDeviceBean implements Bean, PassivationCapable
{
	
	/**
	 * Local logger
	 */
	private static final Logger logger = LoggerFactory.getLogger(ManagedDeviceBean.class);

	public ManagedDeviceBean(Class type, Arduino arduino)
	{
		this.type = type;
		this.arduino = arduino;
	}
	
	private final Class type;
	
	private final Arduino arduino;
	
	private Object instance;
	
	
	@Override
	public Object create(CreationalContext creationalContext)
	{
		if (instance == null)
		{
			logger.debug("Creating instance for type: {}", type);
			arduino.setTargetState(ConnectionState.CONNECTED);
			instance = Managed.create(type, arduino);
		}
		
		return instance;
	}

	@Override
	public void destroy(Object instance, CreationalContext creationalContext)
	{
		logger.debug("Destroying instance for type: {}", type);
		arduino.setTargetState(ConnectionState.DISCONNECTED);
		instance = null;
		
		creationalContext.release();
	}

	@Override
	public Set getTypes()
	{
		Set set = new HashSet<>();
		set.add(Object.class);
		set.add(type);
		set.add(Arduino.class);
		
		return set;
	}

	@Override
	public Set getQualifiers()
	{
		Set set = new HashSet<>();
		set.add(new AnnotationLiteral() {});
		set.add(new AnnotationLiteral() {});
		
		return set;
	}

	@Override
	public Class getScope()
	{
		return ApplicationScoped.class;
	}

	@Override
	public String getName()
	{
		return null;
	}

	@Override
	public Set> getStereotypes()
	{
		return Collections.emptySet();
	}

	@Override
	public boolean isAlternative()
	{
		return false;
	}

	@Override
	public Class getBeanClass()
	{
		return type;
	}

	@Override
	public Set getInjectionPoints()
	{
		return Collections.emptySet();
	}

	@Override
	public boolean isNullable()
	{
		return false;
	}

	@Override
	public String getId()
	{
		return "" + this.hashCode();
	}

}