org.nuiton.jaxx.runtime.application.ApplicationContextComponent Maven / Gradle / Ivy
package org.nuiton.jaxx.runtime.application;
/*-
* #%L
* JAXX :: Runtime
* %%
* Copyright (C) 2008 - 2024 Code Lutin, Ultreia.io
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* .
* #L%
*/
import java.io.Closeable;
import java.util.Objects;
/**
* Created by tchemit on 28/01/2018.
*
* @author Tony Chemit - [email protected]
*/
public abstract class ApplicationContextComponent, O> {
private final Class type;
private final String name;
private O instance;
protected ApplicationContextComponent(Class type, String name) {
this.type = Objects.requireNonNull(type);
this.name = Objects.requireNonNull(name);
}
protected ApplicationContextComponent(Class type) {
this(Objects.requireNonNull(type), type.getSimpleName());
}
protected abstract O load(Context context, Config config);
public final Class getType() {
return type;
}
public final String getName() {
return name;
}
public final boolean isInit() {
return instance != null;
}
public final O get() {
return instance;
}
public final O remove() {
O value = get();
if (value != null) {
try {
if (value instanceof Closeable) {
try {
((Closeable) value).close();
} catch (Exception e) {
throw new RuntimeException("Could not close " + this, e);
}
}
} finally {
this.instance = null;
}
}
return value;
}
@Override
public final boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ApplicationContextComponent, ?, ?> that = (ApplicationContextComponent, ?, ?>) o;
return Objects.equals(name, that.name) &&
Objects.equals(type, that.type);
}
@Override
public final int hashCode() {
return Objects.hash(name, type);
}
public final void set(Context context, Config config) {
set(load(context, config));
}
public final void set(O instance) {
if (this.instance != null) {
throw new IllegalStateException(String.format("%s has already a value: %s", this, this.instance));
}
this.instance = Objects.requireNonNull(instance);
}
}