Skip to content

Instantly share code, notes, and snippets.

@open-ruic
Last active June 6, 2018 08:58
Show Gist options
  • Save open-ruic/cc0c4435b143f66576c6e79cc702f4a5 to your computer and use it in GitHub Desktop.
Save open-ruic/cc0c4435b143f66576c6e79cc702f4a5 to your computer and use it in GitHub Desktop.
Using HK2 with Jersey enabled autoscanning
import org.glassfish.hk2.api.JustInTimeInjectionResolver;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import javax.inject.Singleton;
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
public class AutoScanFeature implements Feature {
@Override
public boolean configure(FeatureContext context) {
context.register(new AbstractBinder() {
@Override
protected void configure() {
bind(JustInTimeServiceResolver.class).to(JustInTimeInjectionResolver.class).in(Singleton.class);
}
});
return false;
}
}
# use reflections to scan HK2 annotation
compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.25.1'
compile 'org.reflections:reflections:0.9.10'
import com.rapid.develop.core.ApplicationConfig;
import org.glassfish.hk2.api.ActiveDescriptor;
import org.glassfish.hk2.api.Injectee;
import org.glassfish.hk2.api.JustInTimeInjectionResolver;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.utilities.ServiceLocatorUtilities;
import org.jvnet.hk2.annotations.Contract;
import javax.inject.Inject;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class JustInTimeServiceResolver implements JustInTimeInjectionResolver {
@Inject
private ServiceLocator serviceLocator;
@Inject
private ApplicationConfig config;
@Override
public boolean justInTimeResolution(Injectee injectee) {
final Type requiredType = injectee.getRequiredType();
if ( injectee.getRequiredQualifiers().isEmpty() && requiredType instanceof Class ) {
final Class<?> requiredClass = (Class<?>) requiredType;
if (isInScanPackages(requiredClass.getPackage().getName())) {
final List<ActiveDescriptor<?>> descriptors = new ArrayList<>();
if(requiredClass.isAnnotationPresent(Contract.class)) {
Set<Class<?>> classes = config.getReflections().getSubTypesOf(((Class) requiredClass));
for(Class subClass : classes) {
descriptors.addAll(ServiceLocatorUtilities.addClasses(serviceLocator, subClass));
}
} else {
descriptors.addAll(ServiceLocatorUtilities.addClasses(serviceLocator, requiredClass));
}
if (!descriptors.isEmpty()) {
return true;
}
}
}
return false;
}
private boolean isInScanPackages(String packageName) {
for(String scanPackage : config.getScanPackages()) {
if(packageName.startsWith(scanPackage)) {
return true;
}
}
return false;
}
}
import com.rapid.develop.core.jersey.features.autoscan.AutoScanFeature;
import com.rapid.develop.core.jersey.features.hibernate.HibernateFeature;
import com.rapid.develop.core.jersey.features.properties.PropertiesFeature;
import com.rapid.develop.core.jersey.features.session.SessionFeature;
import com.rapid.develop.core.jersey.features.mongodb.MongoFeature;
import com.rapid.develop.core.jersey.features.quartz.QuartzFeature;
import com.rapid.develop.core.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.logging.LoggingFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.reflections.Reflections;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
@Singleton
public class ApplicationConfig extends ResourceConfig {
private static final String APP_CONFIG_SYSTEM_VAR = "application.configFile";
private final static String APPLICATION_PROPERTIES_FILE = "application.properties";
private final static String SCAN_PACKAGES = "app.scan.packages";
private ServiceLocator locator;
private String[] scanPackages = {};
private Reflections reflections = null;
@Inject
public ApplicationConfig(final ServiceLocator locator) {
this.locator = locator;
this.loadProperties();
packages(true, getProperty(SCAN_PACKAGES).toString());
register(AutoScanFeature.class);
register(SessionFeature.class);
register(PropertiesFeature.class);
register(QuartzFeature.class);
register(HibernateFeature.class);
register(MongoFeature.class);
register(LoggingFeature.class);
register(new AbstractBinder() {
@Override
protected void configure() {
bind(ServletContainer.class).to(ServletContainer.class).in(Singleton.class);
}
});
}
private void loadProperties() throws ConfigurationException {
InputStream inputStream = null;
try {
Properties prop = new Properties();
if (StringUtils.isNotEmpty(System.getProperty(APP_CONFIG_SYSTEM_VAR))) {
inputStream = new FileInputStream(new File(System.getProperty(APP_CONFIG_SYSTEM_VAR)));
} else {
inputStream = ApplicationConfig.class.getClassLoader().getResourceAsStream(APPLICATION_PROPERTIES_FILE);
}
prop.load(inputStream);
for(Map.Entry<Object, Object> entry : prop.entrySet()) {
property(entry.getKey().toString(), entry.getValue());
}
} catch (IOException e) {
throw new ConfigurationException("Unable access specified properties file [ application.properties ]", e);
} finally {
IOUtils.closeQuietly(inputStream);
}
}
public <T> T getService(Class<T> contractOrImpl) {
return locator.getService(contractOrImpl);
}
public String get(String key, String defaultValue) {
String value = (String) this.getProperties().get(key);
if(StringUtils.isEmpty(value)) {
return defaultValue;
}
return value;
}
public String get(String key) {
String value = (String) this.getProperties().get(key);
return value;
}
public String[] getScanPackages() {
if(scanPackages.length == 0) {
String scanPackagesProperty = this.getProperties().get(ApplicationConfig.SCAN_PACKAGES).toString();
if (StringUtils.isNotEmpty(scanPackagesProperty)) {
scanPackages = scanPackagesProperty.split(",");
}
}
return scanPackages;
}
public Reflections getReflections() {
if (reflections == null) {
reflections = new Reflections(getScanPackages());
}
return reflections;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment