Skip to content

Commit

Permalink
Support for wrapper DI.
Browse files Browse the repository at this point in the history
  • Loading branch information
noboomu committed May 21, 2019
1 parent 5d21d05 commit 22cefa4
Show file tree
Hide file tree
Showing 9 changed files with 111 additions and 65 deletions.
10 changes: 5 additions & 5 deletions core/src/main/java/io/sinistral/proteus/ProteusApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,10 @@
import com.google.inject.name.Named;
import com.typesafe.config.Config;
import io.sinistral.proteus.modules.ConfigModule;
import io.sinistral.proteus.modules.JacksonModule;
import io.sinistral.proteus.server.Extractors;
import io.sinistral.proteus.server.ServerResponse;
import io.sinistral.proteus.server.endpoints.EndpointInfo;
import io.sinistral.proteus.server.handlers.HandlerGenerator;
import io.sinistral.proteus.server.handlers.ServerDefaultHttpHandler;
import io.sinistral.proteus.services.BaseService;
import io.sinistral.proteus.services.DefaultService;
import io.sinistral.proteus.utilities.SecurityOps;
import io.sinistral.proteus.utilities.TablePrinter;
import io.undertow.Undertow;
Expand All @@ -48,7 +44,11 @@
import java.nio.file.Paths;
import java.security.KeyStore;
import java.time.Duration;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
package io.sinistral.proteus.modules;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
Expand All @@ -16,7 +12,6 @@
import io.sinistral.proteus.server.ServerResponse;
import io.sinistral.proteus.server.endpoints.EndpointInfo;
import io.sinistral.proteus.services.BaseService;
import io.sinistral.proteus.services.DefaultService;
import io.sinistral.proteus.wrappers.JsonViewWrapper;
import io.undertow.server.DefaultResponseListener;
import io.undertow.server.HandlerWrapper;
Expand All @@ -39,6 +34,7 @@ public class ApplicationModule extends AbstractModule
protected Set<Class<?>> registeredControllers = new HashSet<>();
protected Set<Class<? extends BaseService>> registeredServices = new HashSet<>();
protected Map<String, HandlerWrapper> registeredHandlerWrappers = new HashMap<>();

protected Config config;

public ApplicationModule(Config config)
Expand Down Expand Up @@ -148,6 +144,7 @@ protected void configure()
this.bind(new TypeLiteral<Map<String, HandlerWrapper>>()
{
}).annotatedWith(Names.named("registeredHandlerWrappers")).toInstance(registeredHandlerWrappers);

}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.google.inject.Inject;
import io.sinistral.proteus.server.predicates.ServerPredicates;
import io.sinistral.proteus.wrappers.JsonViewWrapper;
import io.sinistral.proteus.test.wrappers.JsonViewWrapper;
import io.undertow.io.IoCallback;
import io.undertow.server.DefaultResponseListener;
import io.undertow.server.HttpHandler;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ public enum StatementParameterType
@Named("registeredHandlerWrappers")
protected Map<String, HandlerWrapper> registeredHandlerWrappers;

protected Map<Class<? extends HandlerWrapper>, String> typeLevelHandlerWrapperMap = new LinkedHashMap<>();
protected Map<String, Class<? extends HandlerWrapper>> registeredWrapperTypes = new HashMap<>();

protected Map<Class<? extends HandlerWrapper>, String> handlerWrapperMap = new LinkedHashMap<>();
protected Map<Class<? extends HandlerWrapper>, String> typeLevelHandlerWrapperMap = new LinkedHashMap<>();

/**
* Create a new {@code HandlerGenerator} instance used to generate a
Expand Down Expand Up @@ -129,51 +129,6 @@ protected void generateRoutes()
{
try {

// Optional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(controllerClass.getAnnotation(io.sinistral.proteus.annotations.Chain.class));
//
// typeLevelWrapAnnotation.ifPresent( a -> {
//
// io.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();
//
// Class<? extends HandlerWrapper> wrapperClasses[] = w.value();
//
// for (int i = 0; i < wrapperClasses.length; i++)
// {
// Class<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];
//
// String wrapperName = generateFieldName(wrapperClass.getCanonicalName());
//
// handlerWrapperMap.put(wrapperClass, wrapperName);
// }
//
// });
//
// for(Method m : this.controllerClass.getDeclaredMethods())
// {
//
// Optional<io.sinistral.proteus.annotations.Chain> methodLevelWrapAnnotation = Optional.ofNullable(m.getAnnotation(io.sinistral.proteus.annotations.Chain.class));
//
// methodLevelWrapAnnotation.ifPresent( a -> {
//
// io.sinistral.proteus.annotations.Chain w = methodLevelWrapAnnotation.get();
//
// Class<? extends HandlerWrapper> wrapperClasses[] = w.value();
//
// for (int i = 0; i < wrapperClasses.length; i++)
// {
// Class<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];
//
// String wrapperName = generateFieldName(wrapperClass.getCanonicalName());
//
// handlerWrapperMap.put(wrapperClass, wrapperName);
// }
//
// });
//
// }
//
// log.info("handlerWrapperMap: " + handlerWrapperMap);

TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)
.addSuperinterface(ParameterizedTypeName.get(Supplier.class, RoutingHandler.class));

Expand All @@ -199,7 +154,6 @@ protected void generateRoutes()

typeBuilder.addField(mapOfWrappers, "registeredHandlerWrappers", Modifier.PROTECTED, Modifier.FINAL);


constructor.addParameter(this.controllerClass, className);
constructor.addParameter(annotatedMapOfWrappers, "registeredHandlerWrappers");

Expand All @@ -208,6 +162,17 @@ protected void generateRoutes()

addClassMethodHandlers(typeBuilder, this.controllerClass);

registeredWrapperTypes.forEach((key, value) -> {

TypeName typeName = TypeName.get(value);

typeBuilder.addField(typeName, key, Modifier.PROTECTED, Modifier.FINAL);

constructor.addParameter(typeName, key);

constructor.addStatement("this.$N = $N", key, key);
});

typeBuilder.addMethod(constructor.build());

JavaFile javaFile = JavaFile.builder(packageName, typeBuilder.build()).addStaticImport(extractorClass, "*").build();
Expand Down Expand Up @@ -329,16 +294,20 @@ protected void addClassMethodHandlers(TypeSpec.Builder typeBuilder, Class<?> cla

Optional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(clazz.getAnnotation(io.sinistral.proteus.annotations.Chain.class));

/*
CLASS LEVEL WRAPPERS
*/

if (typeLevelWrapAnnotation.isPresent()) {
io.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();

Class<? extends HandlerWrapper>[] wrapperClasses = w.value();

for (Class<? extends HandlerWrapper> wrapperClass : wrapperClasses) {

String wrapperName = generateFieldName(wrapperClass.getCanonicalName());

initBuilder.addStatement("final $T $L = new $T()", wrapperClass, wrapperName, wrapperClass);
registeredWrapperTypes.put(wrapperName,wrapperClass);

typeLevelHandlerWrapperMap.put(wrapperClass, wrapperName);
}
Expand Down Expand Up @@ -821,6 +790,8 @@ protected void addClassMethodHandlers(TypeSpec.Builder typeBuilder, Class<?> cla

}



if (wrapAnnotation.isPresent() || typeLevelHandlerWrapperMap.size() > 0 || securityDefinitions.size() > 0) {
initBuilder.addStatement("currentHandler = $L", handlerName);

Expand All @@ -835,16 +806,22 @@ protected void addClassMethodHandlers(TypeSpec.Builder typeBuilder, Class<?> cla
if (wrapperName == null) {
wrapperName = String.format("%s_%d", generateFieldName(wrapperClass.getCanonicalName()), handlerWrapperIndex++);

initBuilder.addStatement("final $T $L = new $T()", wrapperClass, wrapperName, wrapperClass);

}

initBuilder.addStatement("currentHandler = $L.wrap($L)", wrapperName, "currentHandler");

registeredWrapperTypes.put(wrapperName,wrapperClass);

}
}

for (Class<? extends HandlerWrapper> wrapperClass : typeLevelHandlerWrapperMap.keySet()) {
String wrapperName = typeLevelHandlerWrapperMap.get(wrapperClass);
initBuilder.addStatement("currentHandler = $L.wrap($L)", wrapperName, "currentHandler");

registeredWrapperTypes.put(wrapperName,wrapperClass);

}

for (String securityDefinitionName : securityDefinitions) {
Expand All @@ -856,6 +833,8 @@ protected void addClassMethodHandlers(TypeSpec.Builder typeBuilder, Class<?> cla
initBuilder.addStatement("$L.add(io.undertow.util.Methods.$L,$S,$L)", "router", httpMethod, methodPath, handlerName);
}



initBuilder.addCode("$L", "\n");

registeredEndpoints.add(endpointInfo);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package io.sinistral.proteus.test.controllers;

import static io.sinistral.proteus.server.ServerResponse.response;
import static io.sinistral.proteus.test.wrappers.TestWrapper.DEBUG_TEST_KEY;

import java.io.File;
import java.nio.ByteBuffer;
Expand Down Expand Up @@ -37,10 +38,13 @@
import com.google.inject.Singleton;

import io.sinistral.proteus.annotations.Blocking;
import io.sinistral.proteus.annotations.Chain;
import io.sinistral.proteus.server.ServerRequest;
import io.sinistral.proteus.server.ServerResponse;
import io.sinistral.proteus.test.models.User;

import io.sinistral.proteus.test.wrappers.TestClassWrapper;
import io.sinistral.proteus.test.wrappers.TestWrapper;
import io.undertow.server.HttpServerExchange;

/**
Expand All @@ -53,6 +57,7 @@
@Produces((MediaType.APPLICATION_JSON))
@Consumes((MediaType.MEDIA_TYPE_WILDCARD))
@Singleton
@Chain({TestClassWrapper.class})
public class Tests
{
private static final ByteBuffer buffer;
Expand Down Expand Up @@ -351,13 +356,17 @@ public ServerResponse<ByteBuffer> pathParamEndpoint(ServerRequest request, @Path

@GET
@Path("response/debug")
public ServerResponse<Map<String,String>> debugEndpoint(ServerRequest request)
@Chain({TestWrapper.class})
public ServerResponse<Map<String,String>> debugEndpoint(ServerRequest request)
{
try
{
Map<String,String> map = ImmutableMap.of("message", "Hello, World!");
String testString = request.getExchange().getAttachment(DEBUG_TEST_KEY);

Map<String,String> map = ImmutableMap.of("message", "Hello, World!","attachment",testString);

return response( map ).applicationJson();

} catch(Exception e)
{
return response().badRequest(e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public void setUp()
@Test
public void testDebugEndpoint()
{
given().accept(ContentType.JSON).when().get("tests/response/debug").then().statusCode(200);
given().accept(ContentType.JSON).when().get("tests/response/debug").then().statusCode(200).body(containsString("testValue"));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package io.sinistral.proteus.test.wrappers;

import com.google.inject.Inject;
import com.google.inject.name.Named;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.util.AttachmentKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestClassWrapper implements HandlerWrapper
{


@Override
public HttpHandler wrap(HttpHandler handler)
{
return exchange -> {

handler.handleRequest(exchange);
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package io.sinistral.proteus.test.wrappers;

import com.google.inject.Inject;
import com.google.inject.name.Named;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.util.AttachmentKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestWrapper implements HandlerWrapper
{
private static final Logger log = LoggerFactory.getLogger(TestWrapper.class.getName());

public static AttachmentKey<String> DEBUG_TEST_KEY = AttachmentKey.create(String.class);

public TestWrapper()
{
super();
}

@Inject
@Named("test.wrapper.value")
private String wrapperValue;

@Override
public HttpHandler wrap(HttpHandler handler)
{
return exchange -> {

log.debug("Test wrapper");

exchange.putAttachment(DEBUG_TEST_KEY,wrapperValue);

handler.handleRequest(exchange);
};
}
}
2 changes: 1 addition & 1 deletion core/src/test/resources/application.conf
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ assets {

}


test.wrapper.value = "testValue"



Expand Down

0 comments on commit 22cefa4

Please sign in to comment.