Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Injectable WebActors - Undertow #87

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ subprojects {
ext.slf4jApiVer = '1.7.21'
ext.log4jVer = '1.2.17'
ext.guavaVer = '19.0'
ext.guiceVer = '4.1.0'

ext.okhttpVer = '2.6.0' // TODO Upgrade to 3.2.x

Expand Down Expand Up @@ -108,6 +109,7 @@ subprojects {

ext.kafkaClientsVer = '0.9.0.0' // ''0.8.2.2'
ext.shiroVer = '1.2.4'
ext.javaxInjectVer = '1'

configurations.all {
resolutionStrategy {
Expand Down
6 changes: 6 additions & 0 deletions comsat-actors-undertow/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
dependencies {
compile "javax.inject:javax.inject:$javaxInjectVer"
testCompile "com.google.inject:guice:$guiceVer"
testCompile "org.springframework:spring-core:$springVer"
testCompile "org.springframework:spring-context:$springVer"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package co.paralleluniverse.comsat.webactors.undertow;

import co.paralleluniverse.actors.Actor;
import co.paralleluniverse.actors.ActorImpl;
import co.paralleluniverse.actors.ActorRef;
import co.paralleluniverse.actors.ActorSpec;
import co.paralleluniverse.common.reflection.AnnotationUtil;
import co.paralleluniverse.common.reflection.ClassLoaderUtil;
import co.paralleluniverse.common.util.Pair;
import co.paralleluniverse.comsat.webactors.WebActor;
import co.paralleluniverse.comsat.webactors.WebMessage;
import io.undertow.UndertowLogger;
import io.undertow.server.HttpServerExchange;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;

class AutoActorContext extends WebActorHandler.DefaultContextImpl {

private static final List<Class<?>> actorClasses = new ArrayList<>(4);
private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];

private String id;

private final List<String> packagePrefixes;
private final Map<Class<?>, Object[]> actorParams;
private final ClassLoader userClassLoader;
private Class<? extends ActorImpl<? extends WebMessage>> actorClass;
private ActorRef<? extends WebMessage> actorRef;

public AutoActorContext(HttpServerExchange xch, List<String> packagePrefixes, Map<Class<?>, Object[]> actorParams, ClassLoader userClassLoader) {
this.packagePrefixes = packagePrefixes;
this.actorParams = actorParams;
this.userClassLoader = userClassLoader;
}

private void fillActor(HttpServerExchange xch) {
final Pair<ActorRef<? extends WebMessage>, Class<? extends ActorImpl<? extends WebMessage>>> p = autoCreateActor(xch);
if (p != null) {
actorRef = p.getFirst();
actorClass = p.getSecond();
}
}

@Override
public final String getId() {
return id != null ? id : (id = UUID.randomUUID().toString());
}

@Override
public final void restart(HttpServerExchange xch) {
renewed = new Date().getTime();
fillActor(xch);
}

@Override
public final ActorRef<? extends WebMessage> getWebActor() {
return actorRef;
}

@Override
public final boolean handlesWithWebSocket(String uri) {
return WebActorHandler.handlesWithWebSocket(uri, actorClass);
}

@Override
public final boolean handlesWithHttp(String uri) {
return WebActorHandler.handlesWithHttp(uri, actorClass);
}

@Override
public WatchPolicy watch() {
return WatchPolicy.DIE_IF_EXCEPTION_ELSE_RESTART;
}

@SuppressWarnings("unchecked")
private Pair<ActorRef<? extends WebMessage>, Class<? extends ActorImpl<? extends WebMessage>>> autoCreateActor(HttpServerExchange xch) {
registerActorClasses();
final String uri = xch.getRequestURI();
for (final Class<?> c : actorClasses) {
if (WebActorHandler.handlesWithHttp(uri, c) || WebActorHandler.handlesWithWebSocket(uri, c))
return new Pair<ActorRef<? extends WebMessage>, Class<? extends ActorImpl<? extends WebMessage>>>(
spawnActor(c), (Class<? extends ActorImpl<? extends WebMessage>>) c
);
}

return null;
}

@SuppressWarnings("unchecked")
protected ActorRef spawnActor(Class<?> c) {
return Actor.newActor(new ActorSpec(c, actorParams != null ? actorParams.get(c) : EMPTY_OBJECT_ARRAY)).spawn();
}

private synchronized void registerActorClasses() {
if (actorClasses.isEmpty()) {
try {
final ClassLoader classLoader = userClassLoader != null ? userClassLoader : this.getClass().getClassLoader();
ClassLoaderUtil.accept((URLClassLoader) classLoader, new ClassLoaderUtil.Visitor() {
@Override
public final void visit(String resource, URL url, ClassLoader cl) {
if (packagePrefixes != null) {
boolean found = false;
for (final String packagePrefix : packagePrefixes) {
if (packagePrefix != null && resource.startsWith(packagePrefix.replace('.', '/'))) {
found = true;
break;
}
}
if (!found)
return;
}
if (!ClassLoaderUtil.isClassFile(resource))
return;
final String className = ClassLoaderUtil.resourceToClass(resource);
try (final InputStream is = cl.getResourceAsStream(resource)) {
if (AnnotationUtil.hasClassAnnotation(WebActor.class, is))
registerWebActor(cl.loadClass(className));
} catch (final IOException | ClassNotFoundException e) {
UndertowLogger.ROOT_LOGGER.error("Exception while scanning class " + className + " for WebActor annotation", e);
throw new RuntimeException(e);
}
}

private void registerWebActor(Class<?> c) {
actorClasses.add(c);
}
});
} catch (final IOException e) {
UndertowLogger.ROOT_LOGGER.error("IOException while scanning classes for WebActor annotation", e);
}
}
}

public void init(HttpServerExchange xch) {
fillActor(xch);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package co.paralleluniverse.comsat.webactors.undertow;

import io.undertow.server.HttpServerExchange;
import io.undertow.server.session.Session;
import io.undertow.util.Sessions;

import java.util.List;
import java.util.Map;

import static co.paralleluniverse.comsat.webactors.undertow.WebActorHandler.ACTOR_KEY;

class AutoContextProvider implements WebActorHandler.ContextProvider {
private final ClassLoader userClassLoader;
private final Map<Class<?>, Object[]> actorParams;
private final Long defaultContextValidityMS;
private final List<String> packagePrefixes;

public AutoContextProvider(ClassLoader userClassLoader, List<String> packagePrefixes, Map<Class<?>, Object[]> actorParams) {
this(userClassLoader, packagePrefixes, actorParams, null);
}

public AutoContextProvider(ClassLoader userClassLoader, List<String> packagePrefixes, Map<Class<?>, Object[]> actorParams, Long defaultContextValidityMS) {
this.userClassLoader = userClassLoader;
this.packagePrefixes = packagePrefixes;
this.actorParams = actorParams;
this.defaultContextValidityMS = defaultContextValidityMS;
}

@Override
public final WebActorHandler.Context get(final HttpServerExchange xch) {
WebActorHandler.Context actorContext;
Session session = null;
try {
session = Sessions.getOrCreateSession(xch);
} catch (final IllegalStateException ignored) {
} // No session handler

if (session != null) {
actorContext = (WebActorHandler.Context) session.getAttribute(ACTOR_KEY);
if (actorContext == null || !actorContext.renew()) {
actorContext = newContext(xch);
session.setAttribute(ACTOR_KEY, actorContext);
}
} else {
actorContext = newContext(xch);
}

return actorContext;
}

private WebActorHandler.Context newContext(final HttpServerExchange xch) {
final AutoActorContext c = createContext(xch);
c.init(xch);
if (defaultContextValidityMS != null)
c.setValidityMS(defaultContextValidityMS);
return c;
}

protected AutoActorContext createContext(HttpServerExchange xch) {
return new AutoActorContext(xch, packagePrefixes, actorParams, userClassLoader);
}

public ClassLoader getUserClassLoader() {
return userClassLoader;
}

public List<String> getPackagePrefixes() {
return packagePrefixes;
}
}
Loading