Skip to content

Commit

Permalink
Generator progress.
Browse files Browse the repository at this point in the history
  • Loading branch information
noboomu committed Apr 2, 2017
1 parent 6c0ae6c commit 3a47fe0
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 46 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -145,5 +145,10 @@
<artifactId>guice</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>net.openhft</groupId>
<artifactId>compiler</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
</project>
3 changes: 2 additions & 1 deletion src/com/wurrly/controllers/Users.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
Expand Down Expand Up @@ -114,7 +115,7 @@ public Any user(final ServerRequest serverRequest, @PathParam("userId") final Lo
@Path("/")
// @ApiImplicitParams({ @ApiImplicitParam(dataType = "com.wurrly.models.User", name = "user", paramType = "body", required = false, allowMultiple = false) })
@ApiOperation(value = "Find users by id", nickname = "user", httpMethod = "POST", response = JsonNode.class)
public Any createUser(final ServerRequest serverRequest, @QueryParam("context") Optional<String> context, final User user )
public Any createUser(final ServerRequest serverRequest, @QueryParam("context") Optional<String> context, final List<User> user )
{
//

Expand Down
25 changes: 23 additions & 2 deletions src/com/wurrly/server/Extractors.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public static final <T> java.util.Optional<T> typed(final HttpServerExchange exc
});
}

public static final java.util.Optional<Any> any(final HttpServerExchange exchange, final String name)
public static final java.util.Optional<Any> any(final HttpServerExchange exchange )
{
return java.util.Optional.ofNullable(exchange.getAttachment(ServerRequest.JSON_DATA)).map(t -> {

Expand All @@ -58,6 +58,17 @@ public static final java.util.Optional<Integer> integerValue(final HttpServerExc
{
return string(exchange, name).map(Integer::parseInt);
}

public static final java.util.Optional<Float> floatValue(final HttpServerExchange exchange, final String name)
{
return string(exchange, name).map(Float::parseFloat);
}

public static final java.util.Optional<Double> doubleValue(final HttpServerExchange exchange, final String name)
{
return string(exchange, name).map(Double::parseDouble);
}


public static final java.util.Optional<Long> longValue(final HttpServerExchange exchange, final String name)
{
Expand Down Expand Up @@ -90,7 +101,7 @@ public static final <T> T typed(final HttpServerExchange exchange, final TypeLit
return jsonIterator(exchange).read(type);
}

public static final Any any(final HttpServerExchange exchange, final String name)
public static final Any any(final HttpServerExchange exchange )
{
try
{
Expand Down Expand Up @@ -128,6 +139,16 @@ public static final ByteBuffer fileBytes(final HttpServerExchange exchange, fina

}

public static final Float floatValue(final HttpServerExchange exchange, final String name)
{
return Float.parseFloat(string(exchange, name));
}

public static final Double doubleValue(final HttpServerExchange exchange, final String name)
{
return Double.parseDouble(string(exchange, name));
}

public static final String string(final HttpServerExchange exchange, final String name)
{
return exchange.getQueryParameters().get(name).getFirst();
Expand Down
106 changes: 82 additions & 24 deletions src/com/wurrly/tests/TestGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
Expand All @@ -29,7 +31,7 @@
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.TypeSpec;
import com.wurrly.controllers.Users;
import com.wurrly.server.Extractors;
import com.wurrly.server.ServerRequest;
import com.wurrly.utilities.HandleGenerator;

Expand All @@ -50,27 +52,43 @@ public static enum StatementParameterType
STRING,LITERAL,TYPE
}

public static void generateTypeLiteral( MethodSpec.Builder builder, Type type, String name, String reference )
{

builder.addCode(CodeBlock.of("\n\ncom.jsoniter.spi.TypeLiteral<$T> $LType = com.jsoniter.spi.TypeLiteral.create($L);\n\n",type,name,reference));

}


public static void generateParameterReference( MethodSpec.Builder builder, Class<?> clazz )
{

builder.addCode(CodeBlock.of("\n\nType $LType = $T.",clazz,clazz));

}

public static enum TypeHandler
{

LongType("Long $L = Long.parseInt(request.exchange.getQueryParameters().get($S).getFirst())",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
IntegerType("Integer $L = Integer.parseInt(request.exchange.getQueryParameters().get($S).getFirst())",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
StringType("String $L = exchange.getQueryParameters().get($S).getFirst()",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
BooleanType("Boolean $L = Boolean.parseBoolean(exchange.getQueryParameters().get($S).getFirst())",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
FilePathType("Path $L = request.files($S).getFirst().getPath()",true,StatementParameterType.LITERAL,StatementParameterType.STRING),
AnyType("Any $L = exchange.getAttachment(ServerRequest.REQUEST_JSON_BODY).readAny()",true,StatementParameterType.LITERAL),
JsonIteratorType("JsonIterator $L = exchange.getAttachment(ServerRequest.REQUEST_JSON_BODY)",true,StatementParameterType.LITERAL),
ModelType("$T $L = exchange.getAttachment(ServerRequest.REQUEST_JSON_BODY).read($T.class)",true,StatementParameterType.TYPE,StatementParameterType.LITERAL,StatementParameterType.TYPE),

OptionalJsonIteratorType("Optional<JsonIterator> $L = Optional.ofNullable(exchange.getAttachment(ServerRequest.REQUEST_JSON_BODY))",true,StatementParameterType.LITERAL),
OptionalAnyType("Optional<Any> $L = Optional.ofNullable(exchange.getAttachment(ServerRequest.REQUEST_JSON_BODY)).map(JsonIterator::readAny())",true,StatementParameterType.LITERAL),
OptionalStringType("Optional<String> $L = Optional.ofNullable(exchange.getQueryParameters().get($S)).map(Deque::getFirst)",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
OptionalLongType("Optional<Long> $L = Optional.ofNullable(exchange.getQueryParameters().get($S)).map(Deque::getFirst).map(Long::parseLong)",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
OptionalIntegerType("Optional<Integer> $L = Optional.ofNullable(exchange.getQueryParameters().get($S)).map(Deque::getFirst).map(Integer::parseInt)",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
OptionalBooleanType("Optional<Boolean> $L = Optional.ofNullable(exchange.getQueryParameters().get($S)).map(Deque::getFirst).map(Boolean::parseBoolean)",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
OptionalPathType("Optional<Path> $L = Optional.ofNullable(serverRequest.files($S)).map(Deque::getFirst).map(io.undertow.server.form.FormData.FormValue::getPath)",true,StatementParameterType.LITERAL,StatementParameterType.STRING),
LongType("Long $L = Extractors.longValue(exchange,$S)",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
IntegerType("Integer $L = Extractors.integerValue(exchange,$S)",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
StringType("String $L = Extractors.string(exchange,$S)",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
BooleanType("Boolean $L = Extractors.booleanValue(exchange,$S)",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
FilePathType("Path $L = Extractors.filePath(exchange,$S)",true,StatementParameterType.LITERAL,StatementParameterType.STRING),
AnyType("Any $L = Extractors.any(exchange)",true,StatementParameterType.LITERAL),
JsonIteratorType("JsonIterator $L = Extractors.jsonIterator(exchange)",true,StatementParameterType.LITERAL),
ModelType("$T $L = Extractors.typed(exchange,$L)",true,StatementParameterType.TYPE,StatementParameterType.LITERAL,StatementParameterType.LITERAL),
EnumType("$T $L = Extractors.extractEnum(exchange,$L.class,$S)",true,StatementParameterType.TYPE,StatementParameterType.LITERAL,StatementParameterType.LITERAL,StatementParameterType.STRING),

OptionalJsonIteratorType("Optional<JsonIterator> $L = Extractors.Optional.jsonIterator(exchange)",true,StatementParameterType.LITERAL),
OptionalAnyType("Optional<Any> $L = Extractors.Optional.any(exchange)",true,StatementParameterType.LITERAL),
OptionalStringType("Optional<String> $L = Extractors.Optional.string(exchange,$S)",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
OptionalLongType("Optional<Long> $L = Extractors.Optional.longValue(exchange,$S)",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
OptionalIntegerType("Optional<Integer> $L = Extractors.Optional.integerValue(exchange,$S)",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
OptionalBooleanType("Optional<Boolean> $L = Extractors.Optional.booleanValue(exchange,$S)",false,StatementParameterType.LITERAL,StatementParameterType.STRING),
OptionalPathType("Optional<Path> $L = Extractors.Optional.filePath(exchange,$S)",true,StatementParameterType.LITERAL,StatementParameterType.STRING),

;
;

public boolean isBlocking()
{
Expand Down Expand Up @@ -99,6 +117,8 @@ public static void addStatement(MethodSpec.Builder builder, Parameter parameter)
{
TypeHandler handler = forType(parameter.getParameterizedType());



Object[] args = new Object[handler.parameterTypes.length];

for( int i = 0; i < handler.parameterTypes.length; i++ )
Expand All @@ -119,13 +139,25 @@ public static void addStatement(MethodSpec.Builder builder, Parameter parameter)

}
}
builder.addStatement( handler.statement, args);
}

public static TypeHandler forType( Type type ) throws Exception
{
log.debug(type.getTypeName() + " " + type.toString());
boolean isEnum = false;

try
{
Class<?> clazz = Class.forName(type.getTypeName());
isEnum = clazz.isEnum();

} catch (Exception e)
{
// TODO: handle exception
}

log.debug(type.getTypeName() + " " + type.toString() + " is enum " + isEnum);

if( type.equals( Long.class ) )
{
Expand Down Expand Up @@ -182,7 +214,11 @@ else if( type.getTypeName().contains("java.nio.file.Path"))
throw new Exception("No type handler found!");
}
}
else
else if( isEnum )
{
return EnumType;
}
else
{
return ModelType;
}
Expand Down Expand Up @@ -213,6 +249,8 @@ public static void main(String[] args)
ClassName formParserDefinitionClass = ClassName.get("io.undertow.server.form", "MultiPartParserDefinition" );

ClassName.get("io.undertow","Undertow");
ClassName extractors = ClassName.get("com.wurrly.server","Extractors");

ClassName.get("io.undertow","UndertowOptions");
ClassName exchangeClass = ClassName.get("io.undertow.server","HttpServerExchange");
ClassName.get("io.undertow.server","RoutingHandler");
Expand Down Expand Up @@ -256,7 +294,6 @@ public static void addClassMethodHandlers( TypeSpec.Builder typeBuilder, Class<?
ClassName exchangeClass = ClassName.get("io.undertow.server","HttpServerExchange");




String controllerName = clazz.getSimpleName().toLowerCase() + "Controller";

Expand All @@ -272,7 +309,7 @@ public static void addClassMethodHandlers( TypeSpec.Builder typeBuilder, Class<?
MethodSpec.Builder initBuilder = MethodSpec.methodBuilder("addRouteHandlers").addModifiers(Modifier.PUBLIC)
.addParameter(ParameterSpec.builder( io.undertow.server.RoutingHandler.class, "router", Modifier.FINAL).build());

for( Method m : Users.class.getDeclaredMethods() )
for( Method m : com.wurrly.controllers.Users.class.getDeclaredMethods() )
{
String methodPath = HandleGenerator.extractPathTemplate.apply(m);

Expand All @@ -295,9 +332,17 @@ public static void addClassMethodHandlers( TypeSpec.Builder typeBuilder, Class<?
.addException(ClassName.get("java.lang","Exception"))
.addAnnotation(Override.class)
.addParameter(ParameterSpec.builder(HttpServerExchange.class, "exchange", Modifier.FINAL).build());






System.out.println(" " + (new LinkedList<String>()).getClass());

for( Parameter p : m.getParameters() )
{
System.out.println(" p type: " + p.getParameterizedType());

if(p.getParameterizedType().equals(ServerRequest.class))
{
continue;
Expand All @@ -307,6 +352,19 @@ public static void addClassMethodHandlers( TypeSpec.Builder typeBuilder, Class<?
{
TypeHandler t = TypeHandler.forType(p.getParameterizedType());

if( t.equals(TypeHandler.ModelType) )
{
generateTypeLiteral(initBuilder,(Type)p.getParameterizedType(),p.getName(),"");


}


Method m2 = Extractors.class.getMethod("string", HttpServerExchange.class, String.class);

log.debug(m2.getName());
log.debug(m2.toString());

log.debug("t handler: " + t.name());
if(t.isBlocking())
{
Expand Down
39 changes: 20 additions & 19 deletions src/com/wurrly/utilities/HandleGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@
import static java.lang.invoke.MethodHandles.lookup;

import java.io.File;
import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URL;
Expand All @@ -22,27 +20,24 @@
import java.util.Deque;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import java.util.function.Function;

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

import com.google.common.base.Throwables;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jsoniter.spi.TypeLiteral;
import com.wurrly.controllers.Users;
import com.wurrly.models.User;
import com.wurrly.server.Extractors;
import com.wurrly.server.ServerRequest;

import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.form.FormData;
import io.undertow.server.handlers.form.FormDataParser;
import io.undertow.server.handlers.form.FormData.FormValue;
import io.undertow.server.handlers.form.FormDataParser;
import io.undertow.util.Headers;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
Expand Down Expand Up @@ -175,30 +170,30 @@ public static HttpHandler generateHandler(final Users target, final Method targ
//
//
//
// for( int i = 1; i < targetMethod.getParameterCount(); i++ )
// {
// final Parameter p = targetMethod.getParameters()[i];
// parameterNames[i] = p.getName();
// types[i] = p.getParameterizedType();
//
for( int i = 1; i < targetMethod.getParameterCount(); i++ )
{
final Parameter p = targetMethod.getParameters()[i];
parameterNames[i] = p.getName();
types[i] = p.getParameterizedType();

// Logger.debug("Type: " + types[i]);
//
// if( types[i].equals(Long.class) )
// {
// Logger.debug("Long type");
//
// biFunctions[i] = extractLong;
// //biFunctions[i] = extractLong;
// }
// else if( types[i].equals(String.class) )
// {
// Logger.debug("String type");
//
// biFunctions[i] = extractString;
// //biFunctions[i] = extractString;
// }
// else if( types[i].equals(java.nio.file.Path.class) )
// {
// Logger.debug("Path type");
// biFunctions[i] = extractFilePath;
// //biFunctions[i] = extractFilePath;
// }
// else if( types[i].equals(Any.class) )
// {
Expand All @@ -217,8 +212,8 @@ public static HttpHandler generateHandler(final Users target, final Method targ
// }
//
// }
//
// }

}

// final Object[] args = new Object[targetMethod.getParameterCount()];

Expand Down Expand Up @@ -251,13 +246,19 @@ public void handleRequest(final HttpServerExchange exchange) throws Exception

//final Long id = extractLong(exchange,"userId");

java.util.List<com.wurrly.models.User> t;


final Optional<String> context = extractOptional(exchange,"context");
//final User.UserType userType = extractEnum(exchange,"type",User.UserType.class);

// final User user = extractJsonIterator(exchange,"user").read(User.class);

//final Any json = target.userForm(request, id, context, userType, Extractors.fileBytes(exchange, "testFile"));
final Any json = target.createUser(request, context, Extractors.jsonIterator(exchange).read(User.class));

TypeLiteral<List<User>> typeLiteral = TypeLiteral.create(types[2]);

final Any json = target.createUser(request, context, Extractors.typed(exchange, typeLiteral));

// json.whenComplete( ( u, e ) -> {
//
Expand Down

0 comments on commit 3a47fe0

Please sign in to comment.