diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml new file mode 100644 index 0000000..1c24f9a --- /dev/null +++ b/.idea/kotlinc.xml @@ -0,0 +1,7 @@ + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..e208459 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..9c35f71 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000..e6ad615 --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,615 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1491529120950 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1.8 + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/conf/logback.xml b/conf/logback.xml index 9140234..4a4eb58 100644 --- a/conf/logback.xml +++ b/conf/logback.xml @@ -20,7 +20,7 @@ - + diff --git a/src/com/wurrly/server/Extractors.java b/src/com/wurrly/server/Extractors.java deleted file mode 100644 index bb8f076..0000000 --- a/src/com/wurrly/server/Extractors.java +++ /dev/null @@ -1,270 +0,0 @@ -/** - * - */ -package com.wurrly.server; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.text.SimpleDateFormat; -import java.time.ZonedDateTime; -import java.util.Arrays; -import java.util.Date; -import java.util.Deque; -import java.util.function.Function; - -import com.jsoniter.JsonIterator; -import com.jsoniter.any.Any; -import com.jsoniter.spi.TypeLiteral; - -import io.undertow.server.HttpServerExchange; -import io.undertow.server.handlers.form.FormDataParser; -import io.undertow.server.handlers.form.FormData.FormValue; -import io.undertow.util.HttpString; -import io.undertow.util.Methods; - -/** - * @author jbauer - */ -public class Extractors -{ - public static class Optional - { - - public static final java.util.Optional jsonIterator(final HttpServerExchange exchange) - { - return java.util.Optional.ofNullable( JsonIterator.parse(exchange.getAttachment(ServerRequest.JSON_DATA).array())); - } - - public static final java.util.Optional typed(final HttpServerExchange exchange, final TypeLiteral type ) - { - return jsonIterator(exchange).map(i -> { - try - { - return i.read(type); - } catch (Exception e) - { - return null; - } - }); - } - - public static final java.util.Optional typed(final HttpServerExchange exchange, final Class type ) - { - return jsonIterator(exchange).map(i -> { - try - { - return i.read(type); - } catch (Exception e) - { - return null; - } - }); - } - - - public static final java.util.Optional any(final HttpServerExchange exchange ) - { - return java.util.Optional.ofNullable(exchange.getAttachment(ServerRequest.JSON_DATA)).map(t -> { - - return JsonIterator.deserialize(t.array()); - - }); - } - - public static final java.util.Optional integerValue(final HttpServerExchange exchange, final String name) - { - return string(exchange, name).map(Integer::parseInt); - } - - public static final java.util.Optional floatValue(final HttpServerExchange exchange, final String name) - { - return string(exchange, name).map(Float::parseFloat); - } - - public static final java.util.Optional doubleValue(final HttpServerExchange exchange, final String name) - { - return string(exchange, name).map(Double::parseDouble); - } - - - public static final java.util.Optional longValue(final HttpServerExchange exchange, final String name) - { - return string(exchange, name).map(Long::parseLong); - } - - public static final java.util.Optional booleanValue(final HttpServerExchange exchange, final String name) - { - return string(exchange, name).map(Boolean::parseBoolean); - } - - public static final > java.util.Optional enumValue(final HttpServerExchange exchange, final Class clazz, final String name) - { - return string(exchange, name).map(e -> Enum.valueOf(clazz, name)); - } - - public static final java.util.Optional string(final HttpServerExchange exchange, final String name) - { - return java.util.Optional.ofNullable(exchange.getQueryParameters().get(name)).map(Deque::getFirst); - } - - public static final java.util.Optional header(final HttpServerExchange exchange, final String name) - { - return java.util.Optional.ofNullable(exchange.getRequestHeaders().get(name)).map(Deque::getFirst); - } - - public static final java.util.Optional filePath(final HttpServerExchange exchange, final String name) - { - return java.util.Optional.ofNullable(exchange.getAttachment(FormDataParser.FORM_DATA).get(name)).map(Deque::getFirst).map(FormValue::getPath); - } - } - - public static Date date(final HttpServerExchange exchange,final String name) throws Throwable { - - return Date.from( ZonedDateTime.parse( string(exchange,name) ).toInstant() ); - - } - - public static final T typed(final HttpServerExchange exchange, final TypeLiteral type ) throws Exception - { - return jsonIterator(exchange).read(type); - } - - public static final T typed(final HttpServerExchange exchange, final Class type ) throws Exception - { - return jsonIterator(exchange).read(type); - } - - public static final Any any(final HttpServerExchange exchange ) - { - try - { - return JsonIterator.parse( exchange.getAttachment(ServerRequest.JSON_DATA).array() ).readAny(); - } catch (IOException e) - { - return Any.wrapNull(); - } - } - - public static final JsonIterator jsonIterator(final HttpServerExchange exchange ) - { - return JsonIterator.parse(exchange.getAttachment(ServerRequest.JSON_DATA).array()); - } - - public static final Path filePath(final HttpServerExchange exchange, final String name) - { - return exchange.getAttachment(FormDataParser.FORM_DATA).get(name).getFirst().getPath(); - } - - public static final ByteBuffer fileBytes(final HttpServerExchange exchange, final String name) throws IOException - { - final Path filePath = filePath(exchange,name); - - try(final FileChannel fileChannel = FileChannel.open(filePath, StandardOpenOption.READ)) - { - final ByteBuffer buffer = ByteBuffer.allocate((int)fileChannel.size()); - - fileChannel.read(buffer); - - buffer.flip(); - - return buffer; - } - - } - - 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(); - } - - public static final String header(final HttpServerExchange exchange, final String name) - { - return exchange.getRequestHeaders().get(name).getFirst(); - } - - public static final Long longValue(final HttpServerExchange exchange, final String name) - { - return Long.parseLong(string(exchange, name)); - } - - public static final Integer integerValue(final HttpServerExchange exchange, final String name) - { - return Integer.parseInt(string(exchange, name)); - } - - public static final Boolean booleanValue(final HttpServerExchange exchange, final String name) - { - return Boolean.parseBoolean(string(exchange, name)); - } - - public static final > E enumValue(final HttpServerExchange exchange, Class clazz,final String name) - { - return Enum.valueOf(clazz, string(exchange, name)); - } - - public final static Function httpMethodFromMethod = (m) -> - { - return Arrays.stream(m.getDeclaredAnnotations()).map( a -> { - - - if( a instanceof javax.ws.rs.POST) - { - return Methods.POST; - } - else if( a instanceof javax.ws.rs.GET) - { - return Methods.GET; - } - else if( a instanceof javax.ws.rs.PUT) - { - return Methods.PUT; - } - else if( a instanceof javax.ws.rs.DELETE) - { - return Methods.DELETE; - } - else if( a instanceof javax.ws.rs.OPTIONS) - { - return Methods.OPTIONS; - } - - else - { - return null; - } - - }).filter( hm -> hm != null ).findFirst().get(); - - }; - - - public final static Function pathTemplateFromMethod = (m) -> - { - javax.ws.rs.Path childPath = m.getDeclaredAnnotation(javax.ws.rs.Path.class); - - javax.ws.rs.Path parentPath = m.getDeclaringClass().getDeclaredAnnotation(javax.ws.rs.Path.class); - - if(!childPath.value().equals("/")) - { - return (parentPath.value() + '/' + childPath.value()).replaceAll("\\/\\/", "\\/") ; - } - - return (parentPath.value() ) ; - - }; - -} diff --git a/src/com/wurrly/Application.java b/src/main/java/com/wurrly/Application.java similarity index 89% rename from src/com/wurrly/Application.java rename to src/main/java/com/wurrly/Application.java index 7c2da7c..d93013f 100644 --- a/src/com/wurrly/Application.java +++ b/src/main/java/com/wurrly/Application.java @@ -19,7 +19,6 @@ import com.google.common.util.concurrent.ServiceManager.Listener; import com.google.inject.Guice; import com.google.inject.Injector; -import com.google.inject.name.Named; import com.typesafe.config.Config; import com.wurrly.controllers.Users; import com.wurrly.modules.ConfigModule; @@ -34,10 +33,8 @@ import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.RoutingHandler; -import io.undertow.server.protocol.http2.Http2UpgradeHandler; import io.undertow.util.Headers; -import static org.fusesource.jansi.Ansi.*; -import static org.fusesource.jansi.Ansi.Color.*; +import io.undertow.util.HttpString; /** * @author jbauer */ @@ -81,11 +78,7 @@ public void start() - Set services = registeredServices.stream().map( sc -> { - - return injector.getInstance(sc); - - }).collect(Collectors.toSet()); + Set services = registeredServices.stream().map( sc -> injector.getInstance(sc)).collect(Collectors.toSet()); this.serviceManager = new ServiceManager(services); @@ -138,7 +131,7 @@ public Undertow buildServer() Set routingInfo = routingModule.getRegisteredRoutes(); //injector.getInstance(Key.get(new TypeLiteral>() {},Names.named("routeInfo"))); - routingInfo.stream().forEachOrdered( r -> sb.append(r.toString() + "\n")); + routingInfo.stream().forEachOrdered( r -> sb.append(r.toString()).append("\n")); log.info("\n\nRegistered the following endpoints: \n\n" + sb.toString()); @@ -151,7 +144,7 @@ public Undertow buildServer() .setSocketOption(org.xnio.Options.BACKLOG, 10000) .setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, false) - .setServerOption(UndertowOptions.MAX_ENTITY_SIZE, 1000000l * 200 ) + .setServerOption(UndertowOptions.MAX_ENTITY_SIZE, 1000000L * 200 ) .setWorkerThreads(Runtime.getRuntime().availableProcessors() * 8) .setHandler( new HttpHandler() { @@ -166,9 +159,9 @@ public void handleRequest(final HttpServerExchange exchange) throws Exception // return; // } -// exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Origin"), "*"); -// exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET, POST, DELETE, PUT, PATCH, OPTIONS"); -// exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Content-Type, api_key, Authorization"); + exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Origin"), "*"); + exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Methods"), "*"); + exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Headers"), "*"); exchange.getResponseHeaders().put(Headers.SERVER, "Bowser"); router.handleRequest(exchange); diff --git a/src/com/wurrly/controllers/Users.java b/src/main/java/com/wurrly/controllers/Users.java similarity index 67% rename from src/com/wurrly/controllers/Users.java rename to src/main/java/com/wurrly/controllers/Users.java index 30d99a4..0f83ebd 100644 --- a/src/com/wurrly/controllers/Users.java +++ b/src/main/java/com/wurrly/controllers/Users.java @@ -4,10 +4,12 @@ package com.wurrly.controllers; import java.nio.ByteBuffer; +import java.util.Date; import java.util.List; import java.util.Optional; import java.util.UUID; +import javax.annotation.Nullable; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; @@ -65,16 +67,38 @@ public Users() @GET @Path("/{userId}/type") @ApiOperation(value = "Find users by id with type", httpMethod = "GET", response = User.class) - public Any userType(@ApiParam(hidden=true)final ServerRequest serverRequest, @PathParam("userId") final Long userId, @QueryParam("context") Optional context, @QueryParam("type") User.UserType type, @QueryParam("uuid") Optional uuid) + public Any userType( + @ApiParam(hidden=true)final ServerRequest serverRequest, @PathParam("userId") final Long userId, + @QueryParam("optionalQueryString") Optional optionalQueryString, + @QueryParam("optionalLong") Optional optionalLong, + @QueryParam("longValue") Long longValue, + @QueryParam("date") @ApiParam(format="date") Date dateValue, + @QueryParam("numbers") List numbers, + + @QueryParam("queryFromString") UUID queryFromString, + @ApiParam(defaultValue="01234567-9ABC-DEF0-1234-56789ABCDEF0", format="uuid") @QueryParam("optionalQueryFromString") Optional optionalQueryFromString, + @ApiParam(defaultValue="01234567-9ABC-DEF0-1234-56789ABCDEF0") @HeaderParam("headerFromString") Optional headerFromString, + @HeaderParam("headerString") String headerString, + @HeaderParam("optionalHeaderString") Optional optionalHeaderString, + @QueryParam("queryEnum") User.UserType queryEnum, + @QueryParam("optionalQueryEnum") Optional optionalQueryEnum + + ) { // - log.debug("uuid: " + uuid); -// log.debug("configuration: " + configuration); + log.debug("optionalQueryFromString: " + optionalQueryFromString); + log.debug("queryFromString: " + queryFromString); + log.debug("optionalQueryString: " + optionalQueryString); + log.debug("headerFromString: " + headerFromString); + log.debug("headerString: " + headerString); + log.debug("optionalHeaderString: " + optionalHeaderString); + log.debug("queryEnum: " + queryEnum); + log.debug("optionalQueryEnum: " + optionalQueryEnum); + log.debug("userId: " + userId); + -// log.debug("context: " + context); -// // - return Any.wrap(new User(userId,type)); + return Any.wrap(new User(232343L)); } @@ -86,7 +110,7 @@ public Any userForm(@ApiParam(hidden=true) final ServerRequest serverRequest, @ApiParam(name="userId",required=true) @PathParam("userId") final Long userId, @ApiParam(name="context",required=false) @QueryParam("context") Optional context, @ApiParam(name="type",required=true) @QueryParam("type") User.UserType type, - ByteBuffer testFile + ByteBuffer testFile ) { // @@ -134,7 +158,7 @@ public Any createUser(@ApiParam(hidden=true)final ServerRequest serverRequest, // log.debug("request: " + serverRequest); // log.debug("file: " + user); - return Any.wrap(new User(34l)); + return Any.wrap(new User(34L)); diff --git a/src/com/wurrly/models/User.java b/src/main/java/com/wurrly/models/User.java similarity index 93% rename from src/com/wurrly/models/User.java rename to src/main/java/com/wurrly/models/User.java index fa17626..b005bd7 100644 --- a/src/com/wurrly/models/User.java +++ b/src/main/java/com/wurrly/models/User.java @@ -7,12 +7,12 @@ public class User { - public static enum UserType + public enum UserType { GUEST,MEMBER,ADMIN } - private Long id = 0l; + private Long id = 0L; @JsonIgnore private UserType type = UserType.GUEST; diff --git a/src/com/wurrly/modules/ConfigModule.java b/src/main/java/com/wurrly/modules/ConfigModule.java similarity index 100% rename from src/com/wurrly/modules/ConfigModule.java rename to src/main/java/com/wurrly/modules/ConfigModule.java diff --git a/src/com/wurrly/modules/RoutingModule.java b/src/main/java/com/wurrly/modules/RoutingModule.java similarity index 100% rename from src/com/wurrly/modules/RoutingModule.java rename to src/main/java/com/wurrly/modules/RoutingModule.java diff --git a/src/main/java/com/wurrly/server/Extractors.java b/src/main/java/com/wurrly/server/Extractors.java new file mode 100644 index 0000000..a3bd2e5 --- /dev/null +++ b/src/main/java/com/wurrly/server/Extractors.java @@ -0,0 +1,293 @@ +/** + * + */ +package com.wurrly.server; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Date; +import java.util.Deque; +import java.util.List; +import java.util.Objects; +import java.util.function.Function; +import java.util.stream.Collectors; + +import com.jsoniter.JsonIterator; +import com.jsoniter.any.Any; +import com.jsoniter.spi.TypeLiteral; + +import io.undertow.server.HttpServerExchange; +import io.undertow.server.handlers.form.FormData.FormValue; +import io.undertow.server.handlers.form.FormDataParser; +import io.undertow.util.HttpString; +import io.undertow.util.Methods; + +/** + * @author jbauer + */ +public class Extractors +{ + public static class Optional + { + + public static java.util.Optional jsonIterator(final HttpServerExchange exchange) + { + return java.util.Optional.ofNullable( JsonIterator.parse(exchange.getAttachment(ServerRequest.JSON_DATA).array())); + } + + public static java.util.Optional typed(final HttpServerExchange exchange, final TypeLiteral type ) + { + return jsonIterator(exchange).map(i -> { + try + { + return i.read(type); + } catch (Exception e) + { + return null; + } + }); + } + + public static java.util.Optional typed(final HttpServerExchange exchange, final Class type ) + { + return jsonIterator(exchange).map(i -> { + try + { + return i.read(type); + } catch (Exception e) + { + return null; + } + }); + } + + + public static java.util.Optional any(final HttpServerExchange exchange ) + { + return java.util.Optional.ofNullable(exchange.getAttachment(ServerRequest.JSON_DATA)).map(t -> JsonIterator.deserialize(t.array())); + } + + public static java.util.Optional integerValue(final HttpServerExchange exchange, final String name) + { + return string(exchange, name).map(Integer::parseInt); + } + + public static java.util.Optional floatValue(final HttpServerExchange exchange, final String name) + { + return string(exchange, name).map(Float::parseFloat); + } + + public static java.util.Optional doubleValue(final HttpServerExchange exchange, final String name) + { + return string(exchange, name).map(Double::parseDouble); + } + + + public static java.util.Optional longValue(final HttpServerExchange exchange, final String name) + { + return string(exchange, name).map(Long::parseLong); + } + + public static java.util.Optional booleanValue(final HttpServerExchange exchange, final String name) + { + return string(exchange, name).map(Boolean::parseBoolean); + } + + public static > java.util.Optional enumValue(final HttpServerExchange exchange, final Class clazz, final String name) + { + return string(exchange, name).map(e -> Enum.valueOf(clazz, name)); + } + + public static java.util.Optional string(final HttpServerExchange exchange, final String name) + { + return java.util.Optional.ofNullable(exchange.getQueryParameters().get(name)).map(Deque::getFirst); + } + + + public static java.util.Optional filePath(final HttpServerExchange exchange, final String name) + { + return java.util.Optional.ofNullable(exchange.getAttachment(FormDataParser.FORM_DATA).get(name)).map(Deque::getFirst).map(FormValue::getPath); + } + } + + public static class Header + { + public static String string(final HttpServerExchange exchange, final String name) + { + return exchange.getRequestHeaders().get(name).getFirst(); + } + + public static class Optional + { + + public static java.util.Optional string(final HttpServerExchange exchange, final String name) + { + return java.util.Optional.ofNullable(exchange.getRequestHeaders().get(name)).map(Deque::getFirst); + } + } + + + } + + public static Date date(final HttpServerExchange exchange,final String name) { + + return Date.from( ZonedDateTime.parse( string(exchange,name) ).toInstant() ); + + } + + public static T typed(final HttpServerExchange exchange, final TypeLiteral type ) + { + try + { + return jsonIterator(exchange).read(type); + } + catch( Exception e ) + { + return null; + } + } + + public static T typed(final HttpServerExchange exchange, final Class type ) + { + try + { + return jsonIterator(exchange).read(type); + } + catch( Exception e ) + { + return null; + } + } + + public static Any any(final HttpServerExchange exchange ) + { + try + { + return JsonIterator.parse( exchange.getAttachment(ServerRequest.JSON_DATA).array() ).readAny(); + } catch (IOException e) + { + return Any.wrapNull(); + } + } + + public static JsonIterator jsonIterator(final HttpServerExchange exchange ) + { + return JsonIterator.parse(exchange.getAttachment(ServerRequest.JSON_DATA).array()); + } + + public static Path filePath(final HttpServerExchange exchange, final String name) + { + return exchange.getAttachment(FormDataParser.FORM_DATA).get(name).getFirst().getPath(); + } + + public static ByteBuffer fileBytes(final HttpServerExchange exchange, final String name) throws IOException + { + final Path filePath = filePath(exchange,name); + + try(final FileChannel fileChannel = FileChannel.open(filePath, StandardOpenOption.READ)) + { + final ByteBuffer buffer = ByteBuffer.allocate((int)fileChannel.size()); + + fileChannel.read(buffer); + + buffer.flip(); + + return buffer; + } + + } + + public static Float floatValue(final HttpServerExchange exchange, final String name) + { + return Float.parseFloat(string(exchange, name)); + } + + public static Double doubleValue(final HttpServerExchange exchange, final String name) + { + return Double.parseDouble(string(exchange, name)); + } + + public static String string(final HttpServerExchange exchange, final String name) + { + return exchange.getQueryParameters().get(name).getFirst(); + } + + public static Long longValue(final HttpServerExchange exchange, final String name) + { + return Long.parseLong(string(exchange, name)); + } + + public static Integer integerValue(final HttpServerExchange exchange, final String name) + { + return Integer.parseInt(string(exchange, name)); + } + + public static Boolean booleanValue(final HttpServerExchange exchange, final String name) + { + return Boolean.parseBoolean(string(exchange, name)); + } + + + + public static > E enumValue(final HttpServerExchange exchange, Class clazz,final String name) + { + return Enum.valueOf(clazz, string(exchange, name)); + } + + + + public static Function httpMethodFromMethod = (m) -> + Arrays.stream(m.getDeclaredAnnotations()).map( a -> { + + + if( a instanceof javax.ws.rs.POST) + { + return Methods.POST; + } + else if( a instanceof javax.ws.rs.GET) + { + return Methods.GET; + } + else if( a instanceof javax.ws.rs.PUT) + { + return Methods.PUT; + } + else if( a instanceof javax.ws.rs.DELETE) + { + return Methods.DELETE; + } + else if( a instanceof javax.ws.rs.OPTIONS) + { + return Methods.OPTIONS; + } + + else + { + return null; + } + + }).filter(Objects::nonNull).findFirst().get(); + + + public static Function pathTemplateFromMethod = (m) -> + { + javax.ws.rs.Path childPath = m.getDeclaredAnnotation(javax.ws.rs.Path.class); + + javax.ws.rs.Path parentPath = m.getDeclaringClass().getDeclaredAnnotation(javax.ws.rs.Path.class); + + if(!childPath.value().equals("/")) + { + return (parentPath.value() + '/' + childPath.value()).replaceAll("\\/\\/", "\\/") ; + } + + return (parentPath.value() ) ; + + }; + +} diff --git a/src/com/wurrly/server/ServerRequest.java b/src/main/java/com/wurrly/server/ServerRequest.java similarity index 97% rename from src/com/wurrly/server/ServerRequest.java rename to src/main/java/com/wurrly/server/ServerRequest.java index b294ba3..e37fe57 100644 --- a/src/com/wurrly/server/ServerRequest.java +++ b/src/main/java/com/wurrly/server/ServerRequest.java @@ -253,21 +253,11 @@ private void parseJson() throws IOException } } - else - { - //Logger.debug("inputstream is not available "); - - } } catch (IOException e) { log.error("IOException: ", e); } - } - else - { - //Logger.debug("inputstream is null "); - } } diff --git a/src/com/wurrly/server/ServerResponse.java b/src/main/java/com/wurrly/server/ServerResponse.java similarity index 95% rename from src/com/wurrly/server/ServerResponse.java rename to src/main/java/com/wurrly/server/ServerResponse.java index 1d15773..205e079 100644 --- a/src/com/wurrly/server/ServerResponse.java +++ b/src/main/java/com/wurrly/server/ServerResponse.java @@ -10,7 +10,7 @@ import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.Cookie; import io.undertow.util.HeaderMap; -import io.undertow.util.StatusCodes;; +import io.undertow.util.StatusCodes; /** * @author jbauer diff --git a/src/com/wurrly/server/handlers/HandlerGenerator.java b/src/main/java/com/wurrly/server/handlers/HandlerGenerator.java similarity index 62% rename from src/com/wurrly/server/handlers/HandlerGenerator.java rename to src/main/java/com/wurrly/server/handlers/HandlerGenerator.java index 799f886..2ee0d14 100644 --- a/src/com/wurrly/server/handlers/HandlerGenerator.java +++ b/src/main/java/com/wurrly/server/handlers/HandlerGenerator.java @@ -63,49 +63,65 @@ public class HandlerGenerator private static final Pattern TYPE_NAME_PATTERN = Pattern.compile("(java\\.util\\.[A-Za-z]+)<([^>]+)", Pattern.DOTALL | Pattern.UNIX_LINES); - public static enum StatementParameterType + public enum StatementParameterType { - STRING, LITERAL, TYPE + STRING, LITERAL, TYPE, RAW } - public static enum TypeHandler + public enum TypeHandler { - LongType("Long $L = com.wurrly.server.Extractors.longValue(exchange,$S)", false, StatementParameterType.LITERAL, StatementParameterType.STRING), - IntegerType("Integer $L = com.wurrly.server.Extractors.integerValue(exchange,$S)", false, StatementParameterType.LITERAL, StatementParameterType.STRING), - StringType("String $L = com.wurrly.server.Extractors.string(exchange,$S)", false, StatementParameterType.LITERAL, StatementParameterType.STRING), - BooleanType("Boolean $L = com.wurrly.server.Extractors.booleanValue(exchange,$S)", false, StatementParameterType.LITERAL, StatementParameterType.STRING), - FilePathType("$T $L = com.wurrly.server.Extractors.filePath(exchange,$S)", true, java.nio.file.Path.class, StatementParameterType.LITERAL, StatementParameterType.STRING), - AnyType("$T $L = com.wurrly.server.Extractors.any(exchange)", true, com.jsoniter.any.Any.class, StatementParameterType.LITERAL), - JsonIteratorType("$T $L = com.wurrly.server.Extractors.jsonIterator(exchange)", true, com.jsoniter.JsonIterator.class, StatementParameterType.LITERAL), + LongType("Long $L = $T.longValue(exchange,$S)", false, StatementParameterType.LITERAL,com.wurrly.server.Extractors.class, StatementParameterType.STRING), + IntegerType("Integer $L = $T.integerValue(exchange,$S)", false, StatementParameterType.LITERAL,com.wurrly.server.Extractors.class, StatementParameterType.STRING), + StringType("String $L = $T.string(exchange,$S)", false, StatementParameterType.LITERAL,com.wurrly.server.Extractors.class, StatementParameterType.STRING), + BooleanType("Boolean $L = $T.booleanValue(exchange,$S)", false, StatementParameterType.LITERAL, com.wurrly.server.Extractors.class, StatementParameterType.STRING), + FilePathType("$T $L = $T.filePath(exchange,$S)", true, java.nio.file.Path.class, StatementParameterType.LITERAL,com.wurrly.server.Extractors.class, StatementParameterType.STRING), + AnyType("$T $L = $T.any(exchange)", true, com.jsoniter.any.Any.class, StatementParameterType.LITERAL,com.wurrly.server.Extractors.class), + JsonIteratorType("$T $L = $T.jsonIterator(exchange)", true, com.jsoniter.JsonIterator.class, StatementParameterType.LITERAL,com.wurrly.server.Extractors.class), ModelType("$T $L = com.wurrly.server.Extractors.typed(exchange,$L)", true, StatementParameterType.TYPE, StatementParameterType.LITERAL, StatementParameterType.LITERAL), - EnumType("$T $L = com.wurrly.server.Extractors.enumValue(exchange,$T.class,$S)", true, StatementParameterType.TYPE, StatementParameterType.LITERAL, StatementParameterType.TYPE, StatementParameterType.STRING), - ByteBufferType("$T $L = com.wurrly.server.Extractors.fileBytes(exchange,$S)", false, java.nio.ByteBuffer.class, StatementParameterType.LITERAL, StatementParameterType.STRING), - DateType("$T $L = com.wurrly.server.Extractors.date(exchange,$S)", false, java.util.Date.class, StatementParameterType.LITERAL, StatementParameterType.STRING), - - ValueOfType("$T $L = $T.valueOf(com.wurrly.server.Extractors.string(exchange,$S))", false, StatementParameterType.TYPE, StatementParameterType.LITERAL, StatementParameterType.TYPE, StatementParameterType.STRING), - FromStringType("$T $L = $T.fromString(com.wurrly.server.Extractors.string(exchange,$S))", false, StatementParameterType.TYPE, StatementParameterType.LITERAL, StatementParameterType.TYPE, StatementParameterType.STRING), - - HeaderValueOfType("$T $L = $T.valueOf(com.wurrly.server.Extractors.headerString(exchange,$S))", false, StatementParameterType.TYPE, StatementParameterType.LITERAL, StatementParameterType.TYPE, StatementParameterType.STRING), - HeaderFromStringType("$T $L = $T.fromString(com.wurrly.server.Extractors.headerString(exchange,$S))", false, StatementParameterType.TYPE, StatementParameterType.LITERAL, StatementParameterType.TYPE, StatementParameterType.STRING), - HeaderStringType("$T $L = com.wurrly.server.Extractors.headerString(exchange,$S)", false, java.lang.String.class, StatementParameterType.LITERAL, StatementParameterType.STRING), - - OptionalJsonIteratorType("$T<$T> $L = com.wurrly.server.Extractors.Optional.jsonIterator(exchange)", true, Optional.class, com.jsoniter.JsonIterator.class, StatementParameterType.LITERAL), - OptionalAnyType("$T<$T> $L = com.wurrly.server.Extractors.Optional.any(exchange)", true, Optional.class, com.jsoniter.any.Any.class, StatementParameterType.LITERAL), - OptionalStringType("$T $L = com.wurrly.server.Extractors.Optional.string(exchange,$S)", false, Optional.class, StatementParameterType.LITERAL, StatementParameterType.STRING), - OptionalLongType("$T $L = com.wurrly.server.Extractors.Optional.longValue(exchange,$S)", false, Optional.class, StatementParameterType.LITERAL, StatementParameterType.STRING), - OptionalIntegerType("$T $L = com.wurrly.server.Extractors.Optional.integerValue(exchange,$S)", false, Optional.class, StatementParameterType.LITERAL, StatementParameterType.STRING), - OptionalBooleanType("$T $L = com.wurrly.server.Extractors.Optional.booleanValue(exchange,$S)", false, Optional.class, StatementParameterType.LITERAL, StatementParameterType.STRING), - OptionalPathType("$T<$T> $L = com.wurrly.server.Extractors.Optional.filePath(exchange,$S)", true, Optional.class, java.nio.file.Path.class, StatementParameterType.LITERAL, StatementParameterType.STRING), - OptionalModelType("$T<$L> $L = com.wurrly.server.Extractors.Optional.typed(exchange,$L)", true, Optional.class, StatementParameterType.LITERAL, StatementParameterType.LITERAL, StatementParameterType.LITERAL), - - OptionalValueOfType("java.util.Optional<$L> $L = com.wurrly.server.Extractors.Optional.string(exchange,$S).map($L::valueOf)", false, StatementParameterType.LITERAL, StatementParameterType.LITERAL, StatementParameterType.STRING, StatementParameterType.LITERAL), - OptionalFromStringType("java.util.Optional<$T> $L = com.wurrly.server.Extractors.Optional.string(exchange,$S).map($T::fromString)", false, StatementParameterType.TYPE, StatementParameterType.LITERAL, StatementParameterType.STRING, StatementParameterType.TYPE), + EnumType("$T $L = $T.enumValue(exchange,$T.class,$S)", true, StatementParameterType.TYPE, StatementParameterType.LITERAL,com.wurrly.server.Extractors.class, StatementParameterType.TYPE, StatementParameterType.STRING), + ByteBufferType("$T $L = $T.fileBytes(exchange,$S)", false, java.nio.ByteBuffer.class, StatementParameterType.LITERAL,com.wurrly.server.Extractors.class, StatementParameterType.STRING), + DateType("$T $L = $T.date(exchange,$S)", false, java.util.Date.class, StatementParameterType.LITERAL, com.wurrly.server.Extractors.class, StatementParameterType.STRING), + FloatType("Integer $L = $T.floatValue(exchange,$S)", false, StatementParameterType.LITERAL, com.wurrly.server.Extractors.class, StatementParameterType.STRING), + DoubleType("Integer $L = $T.doubleValue(exchange,$S)", false, StatementParameterType.LITERAL, com.wurrly.server.Extractors.class, StatementParameterType.STRING), + + ValueOfType("$T $L = $T.valueOf($T.string(exchange,$S))", false, StatementParameterType.TYPE, StatementParameterType.LITERAL, StatementParameterType.TYPE, com.wurrly.server.Extractors.class, StatementParameterType.STRING), + FromStringType("$T $L = $T.fromString($T.string(exchange,$S))", false, StatementParameterType.TYPE, StatementParameterType.LITERAL,StatementParameterType.TYPE, com.wurrly.server.Extractors.class, StatementParameterType.STRING), + + ListType("$T<$T> $L = exchange.getQueryParameters().get($S).stream().map($T::valueOf).collect(java.util.stream.Collectors.toList())",false, java.util.List.class,StatementParameterType.RAW, StatementParameterType.LITERAL, StatementParameterType.STRING, StatementParameterType.RAW ), + + HeaderValueOfType("$T $L = $T.valueOf($T.string(exchange,$S))", false, StatementParameterType.TYPE, StatementParameterType.LITERAL, StatementParameterType.TYPE, com.wurrly.server.Extractors.Header.class, StatementParameterType.STRING), + HeaderFromStringType("$T $L = $T.fromString($T.string(exchange,$S))", false, StatementParameterType.TYPE, StatementParameterType.LITERAL, StatementParameterType.TYPE,com.wurrly.server.Extractors.Header.class, StatementParameterType.STRING), + HeaderStringType("$T $L = $T.string(exchange,$S)", false, java.lang.String.class, StatementParameterType.LITERAL,com.wurrly.server.Extractors.Header.class, StatementParameterType.STRING), + + OptionalHeaderValueOfType("$T<$T> $L = $T.string(exchange,$S).map($T::valueOf)", false,Optional.class, StatementParameterType.RAW, StatementParameterType.LITERAL, com.wurrly.server.Extractors.Header.Optional.class, StatementParameterType.STRING,StatementParameterType.RAW), + OptionalHeaderFromStringType("$T<$T> $L = $T.string(exchange,$S).map($T::fromString)", false, Optional.class, StatementParameterType.RAW, StatementParameterType.LITERAL, com.wurrly.server.Extractors.Header.Optional.class, StatementParameterType.STRING,StatementParameterType.RAW), + OptionalHeaderStringType("$T<$T> $L = $T.string(exchange,$S)", false, Optional.class, java.lang.String.class, StatementParameterType.LITERAL,com.wurrly.server.Extractors.Header.Optional.class, StatementParameterType.STRING), + + + + OptionalJsonIteratorType("$T<$T> $L = $T.jsonIterator(exchange)", true, Optional.class, com.jsoniter.JsonIterator.class, StatementParameterType.LITERAL,com.wurrly.server.Extractors.Optional.class), + OptionalAnyType("$T<$T> $L = $T.any(exchange)", true, Optional.class, com.jsoniter.any.Any.class, StatementParameterType.LITERAL,com.wurrly.server.Extractors.Optional.class), + OptionalStringType("$T $L = $T.string(exchange,$S)", false, Optional.class, StatementParameterType.LITERAL,com.wurrly.server.Extractors.Optional.class, StatementParameterType.STRING), + OptionalLongType("$T $L = $T.longValue(exchange,$S)", false, Optional.class, StatementParameterType.LITERAL, com.wurrly.server.Extractors.Optional.class, StatementParameterType.STRING), + OptionalIntegerType("$T $L = $T.integerValue(exchange,$S)", false, Optional.class, StatementParameterType.LITERAL, com.wurrly.server.Extractors.Optional.class, StatementParameterType.STRING), + OptionalBooleanType("$T $L = $T.booleanValue(exchange,$S)", false, Optional.class, StatementParameterType.LITERAL,com.wurrly.server.Extractors.Optional.class, StatementParameterType.STRING), + OptionalPathType("$T<$T> $L = $T.filePath(exchange,$S)", true, Optional.class, java.nio.file.Path.class, StatementParameterType.LITERAL,com.wurrly.server.Extractors.Optional.class, StatementParameterType.STRING), + OptionalFloatType("$T $L = $T.floatValue(exchange,$S)", false, Optional.class, StatementParameterType.LITERAL, com.wurrly.server.Extractors.Optional.class, StatementParameterType.STRING), + OptionalDoubleType("$T $L = $T.doubleValue(exchange,$S)", false, Optional.class, StatementParameterType.LITERAL, com.wurrly.server.Extractors.Optional.class, StatementParameterType.STRING), + + + OptionalModelType("java.util.Optional<$L> $L = $T.typed(exchange,$L)", true, StatementParameterType.LITERAL, StatementParameterType.LITERAL, com.wurrly.server.Extractors.Optional.class, StatementParameterType.LITERAL), + + OptionalValueOfType("$T<$T> $L = $T.string(exchange,$S).map($T::valueOf)", false, Optional.class, StatementParameterType.RAW, StatementParameterType.LITERAL,com.wurrly.server.Extractors.Optional.class, StatementParameterType.STRING, StatementParameterType.RAW), + OptionalFromStringType("$T<$T> $L = $T.string(exchange,$S).map($T::fromString)", false, Optional.class, StatementParameterType.RAW, StatementParameterType.LITERAL, com.wurrly.server.Extractors.Optional.class, StatementParameterType.STRING, StatementParameterType.RAW), + + //OptionalEnumType("$T $L = $T.enumValue(exchange,$T.class,$S)", true, StatementParameterType.TYPE, StatementParameterType.LITERAL, com.wurrly.server.Extractors.Optional.class, StatementParameterType.RAW, StatementParameterType.STRING), ; public boolean isBlocking() - { + { return this.isBlocking; } @@ -119,17 +135,15 @@ public String statement() final private boolean isBlocking; final private Object[] parameterTypes; - private TypeHandler(String statement, boolean isBlocking, Object... types) + TypeHandler(String statement, boolean isBlocking, Object... types) { this.statement = statement; this.isBlocking = isBlocking; this.parameterTypes = types; } - public static void addStatement(MethodSpec.Builder builder, Parameter parameter) throws Exception - { - TypeHandler handler = forType(parameter.getParameterizedType()); - + public static void addStatement(MethodSpec.Builder builder, Parameter parameter, TypeHandler handler) throws Exception + { Object[] args = new Object[handler.parameterTypes.length]; for (int i = 0; i < handler.parameterTypes.length; i++) @@ -148,6 +162,13 @@ public static void addStatement(MethodSpec.Builder builder, Parameter parameter) case TYPE: args[i] = parameter.getParameterizedType(); break; + case RAW: + { + Type type = parameter.getParameterizedType(); + type = extractErasedType(type); + args[i] = type; + break; + } default: break; } @@ -156,12 +177,22 @@ else if (handler.parameterTypes[i] instanceof Class) { Class clazz = (Class) handler.parameterTypes[i]; - args[i] = ClassName.get(clazz); - } + args[i] = clazz; + + } } + log.debug("type: " + parameter.getParameterizedType().getTypeName() + " : " + handler); builder.addStatement(handler.statement, args); } + + public static void addStatement(MethodSpec.Builder builder, Parameter parameter) throws Exception + { + TypeHandler handler = forType(parameter.getParameterizedType()); + + addStatement(builder,parameter,handler); + + } public static TypeHandler forType(Type type) { @@ -169,8 +200,9 @@ public static TypeHandler forType(Type type) boolean hasValueOf = false; boolean hasFromString = false; boolean isOptional = type.getTypeName().contains("java.util.Optional"); - - if(!isOptional) + boolean isArray = type.getTypeName().contains("java.util.List"); + + if(!isOptional && !isArray) { try { @@ -187,6 +219,13 @@ public static TypeHandler forType(Type type) log.error(e.getMessage(),e); } } + + if( isArray && !isOptional ) + { + return ListType; + } + + // log.debug("type: " + type.getTypeName() + " valueOf: " + hasValueOf + " fromString: " + hasFromString); if (type.equals(Long.class)) { @@ -196,6 +235,14 @@ else if (type.equals(Integer.class)) { return IntegerType; } + else if (type.equals(Float.class)) + { + return FloatType; + } + else if (type.equals(Double.class)) + { + return DoubleType; + } else if (type.equals(java.nio.ByteBuffer.class)) { return ByteBufferType; @@ -238,6 +285,14 @@ else if (type.getTypeName().contains("java.lang.Boolean")) { return OptionalBooleanType; } + else if (type.getTypeName().contains("java.lang.Float")) + { + return OptionalFloatType; + } + else if (type.getTypeName().contains("java.lang.Double")) + { + return OptionalDoubleType; + } else if (type.getTypeName().contains("java.lang.Integer")) { return OptionalIntegerType; @@ -245,11 +300,7 @@ else if (type.getTypeName().contains("java.lang.Integer")) else if (type.getTypeName().contains("java.nio.file.Path")) { return OptionalPathType; - } - else if (type.getTypeName().contains("java.lang.String")) - { - return StringType; - } + } else { try @@ -257,6 +308,8 @@ else if (type.getTypeName().contains("java.lang.String")) Class erasedType = extractErasedType(type); + //log.debug("erasedType: " + erasedType.getTypeName() + " valueOf: " + hasValueOfMethod(erasedType) + " fromString: " + hasFromStringMethod(erasedType)); + if( hasValueOfMethod(erasedType) ) { return OptionalValueOfType; @@ -267,19 +320,15 @@ else if( hasFromStringMethod(erasedType) ) return OptionalFromStringType; } - else - { - return StringType; - } } catch (Exception e) { - return StringType; + log.error("error : " + e.getMessage(),e); + return OptionalStringType; } - - - + + return OptionalStringType; } } else if (isEnum) @@ -353,6 +402,7 @@ public Class> compileClass() { this.generateRoutes(); + log.debug("CLASS:\n" + this.sourceString); return CompilerUtils.CACHED_COMPILER.loadFromJava(packageName + "." + className, this.sourceString); } catch (Exception e) @@ -412,20 +462,17 @@ public void addClassMethodHandlers(TypeSpec.Builder typeBuilder, Class clazz) MethodSpec.Builder initBuilder = MethodSpec.methodBuilder("get").addModifiers(Modifier.PUBLIC).returns(RoutingHandler.class).addStatement("final $T router = new $T()", io.undertow.server.RoutingHandler.class, io.undertow.server.RoutingHandler.class); - final Map typeLiteralsMap = Arrays.stream(clazz.getDeclaredMethods()).flatMap(m -> { - return Arrays.stream(m.getParameters()).map(Parameter::getParameterizedType).filter(t -> t.getTypeName().contains("<")); - }).distinct().filter(t -> { - TypeHandler handler = TypeHandler.forType(t); - return (handler.equals(TypeHandler.ModelType) || handler.equals(TypeHandler.OptionalModelType)); + final Map typeLiteralsMap = Arrays.stream(clazz.getDeclaredMethods()) + .flatMap(m -> Arrays.stream(m.getParameters()).map(Parameter::getParameterizedType) + .filter(t -> t.getTypeName().contains("<"))) + .distinct().filter(t -> { + TypeHandler handler = TypeHandler.forType(t); + return (handler.equals(TypeHandler.ModelType) || handler.equals(TypeHandler.OptionalModelType)); }).collect(Collectors.toMap(java.util.function.Function.identity(), HandlerGenerator::typeLiteralNameForType)); initBuilder.addCode("$L", "\n"); - typeLiteralsMap.forEach((t, n) -> { - - initBuilder.addStatement("final $T<$L> $LType = new $T<$L>(){}", TypeLiteral.class, t, n, TypeLiteral.class, t); - - }); + typeLiteralsMap.forEach((t, n) -> initBuilder.addStatement("final $T<$L> $LType = new $T<$L>(){}", TypeLiteral.class, t, n, TypeLiteral.class, t)); initBuilder.addCode("$L", "\n"); @@ -486,7 +533,7 @@ public void addClassMethodHandlers(TypeSpec.Builder typeBuilder, Class clazz) { log.error(e.getMessage(), e); } - } ; + } methodBuilder.addCode("$L", "\n"); @@ -508,40 +555,68 @@ public void addClassMethodHandlers(TypeSpec.Builder typeBuilder, Class clazz) if (p.isAnnotationPresent(HeaderParam.class)) { - Class t = p.getType(); - - TypeHandler handler = null; + + log.debug("header class: " + type); + + TypeHandler handler = TypeHandler.forType(type); + + log.debug("header typehandler: " + handler); - try + if( handler.equals(TypeHandler.OptionalStringType) ) { - t.getMethod("valueOf", java.lang.String.class); + handler = TypeHandler.OptionalHeaderStringType; + + TypeHandler.addStatement(methodBuilder, p,handler); - handler = TypeHandler.HeaderValueOfType; + } + else if( handler.equals(TypeHandler.OptionalValueOfType) ) + { + handler = TypeHandler.OptionalHeaderValueOfType; + + log.debug("header typehandler: " + handler.statement); - methodBuilder.addStatement(handler.statement, t, p.getName(), t, p.getName()); + TypeHandler.addStatement(methodBuilder, p,handler); - } catch (Exception e) - { } - - try + else if( handler.equals(TypeHandler.OptionalFromStringType) ) { - t.getMethod("fromString", java.lang.String.class); + handler = TypeHandler.OptionalHeaderFromStringType; + log.debug("header typehandler: " + handler.statement); - handler = TypeHandler.HeaderFromStringType; + TypeHandler.addStatement(methodBuilder, p,handler); + + } + else if( handler.equals(TypeHandler.StringType) ) + { + handler = TypeHandler.HeaderStringType; + log.debug("header typehandler: " + handler.statement); - methodBuilder.addStatement(handler.statement, t, p.getName(), t, p.getName()); + TypeHandler.addStatement(methodBuilder, p,handler); + + } + else if( handler.equals(TypeHandler.ValueOfType) ) + { + handler = TypeHandler.HeaderValueOfType; + log.debug("header typehandler: " + handler.statement); - } catch (Exception e) + TypeHandler.addStatement(methodBuilder, p,handler); + + } + else if( handler.equals(TypeHandler.FromStringType) ) { + handler = TypeHandler.HeaderFromStringType; + log.debug("header typehandler: " + handler.statement); + TypeHandler.addStatement(methodBuilder, p,handler); + } + - if (handler == null) + else { handler = TypeHandler.HeaderStringType; - methodBuilder.addStatement(handler.statement, p.getName(), p.getName()); + TypeHandler.addStatement(methodBuilder, p,handler); } @@ -562,7 +637,7 @@ else if (t.equals(TypeHandler.OptionalFromStringType) || t.equals(TypeHandler.Op { Class erasedType = extractErasedType(p.getParameterizedType()); - methodBuilder.addStatement(t.statement, erasedType, p.getName(), p.getName(), erasedType); + TypeHandler.addStatement(methodBuilder,p); } else { @@ -582,7 +657,7 @@ else if (t.equals(TypeHandler.OptionalFromStringType) || t.equals(TypeHandler.Op CodeBlock.Builder functionBlockBuilder = CodeBlock.builder(); - String controllerMethodArgs = Arrays.stream(m.getParameters()).map(p -> p.getName()).collect(Collectors.joining(",")); + String controllerMethodArgs = Arrays.stream(m.getParameters()).map(Parameter::getName).collect(Collectors.joining(",")); if (!m.getReturnType().equals(Void.class)) { @@ -706,19 +781,20 @@ public static ArrayList getClassNamesFromPackage(String packageName) thr { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL packageURL; - ArrayList names = new ArrayList();; + ArrayList names = new ArrayList<>(); packageName = packageName.replace(".", "/"); packageURL = classLoader.getResource(packageName); - //log.debug(packageURL + ""); + assert packageURL != null; URI uri = new URI(packageURL.toString()); File folder = new File(uri.getPath()); // won't work with path which contains blank (%20) // File folder = new File(packageURL.getFile()); File[] contenuti = folder.listFiles(); String entryName; + assert contenuti != null; for (File actual : contenuti) { if (actual.isDirectory()) @@ -746,14 +822,7 @@ public static Set> getApiClasses(String basePath, Predicate pat Path annotation = clazz.getDeclaredAnnotation(Path.class); - if (annotation != null) - { - return pathPredicate.test(annotation.value()); - } - else - { - return false; - } + return annotation != null && pathPredicate.test(annotation.value()); }); } @@ -762,6 +831,8 @@ public static Set> getApiClasses(String basePath, Predicate pat } + + public static Class extractErasedType(Type type) throws Exception { String typeName = type.getTypeName(); @@ -776,9 +847,20 @@ public static Class extractErasedType(Type type) throws Exception if (matches == 2) { - String erasedType = matcher.group(2).replaceAll("\\$", "."); + String erasedType = matcher.group(2); + + String clearDollarType = erasedType.replaceAll("\\$", "."); + + try + { + return Class.forName(clearDollarType); + + } catch (Exception e) + { + return Class.forName(erasedType); + } - return Class.forName(erasedType); + } } @@ -806,7 +888,7 @@ public static String typeLiteralNameForType(Type type) String[] erasedParts = erasedType.split("\\."); String genericTypeName = genericParts[genericParts.length - 1]; - String erasedTypeName = null; + String erasedTypeName; if (erasedParts.length > 1) { diff --git a/src/com/wurrly/server/handlers/benchmark/BenchmarkHandlers.java b/src/main/java/com/wurrly/server/handlers/benchmark/BenchmarkHandlers.java similarity index 100% rename from src/com/wurrly/server/handlers/benchmark/BenchmarkHandlers.java rename to src/main/java/com/wurrly/server/handlers/benchmark/BenchmarkHandlers.java diff --git a/src/com/wurrly/server/route/RouteInfo.java b/src/main/java/com/wurrly/server/route/RouteInfo.java similarity index 98% rename from src/com/wurrly/server/route/RouteInfo.java rename to src/main/java/com/wurrly/server/route/RouteInfo.java index e7cd349..c2eb815 100644 --- a/src/com/wurrly/server/route/RouteInfo.java +++ b/src/main/java/com/wurrly/server/route/RouteInfo.java @@ -146,8 +146,8 @@ public int hashCode() toHashCode(); } - public int compareTo(RouteInfo o) { - RouteInfo other = (RouteInfo) o; + public int compareTo(RouteInfo other) { + return new CompareToBuilder() .append(this.controllerName, other.controllerName) .append(this.method, other.method) diff --git a/src/com/wurrly/server/swagger/AnnotationHelper.java b/src/main/java/com/wurrly/server/swagger/AnnotationHelper.java similarity index 100% rename from src/com/wurrly/server/swagger/AnnotationHelper.java rename to src/main/java/com/wurrly/server/swagger/AnnotationHelper.java diff --git a/src/com/wurrly/server/swagger/Reader.java b/src/main/java/com/wurrly/server/swagger/Reader.java similarity index 97% rename from src/com/wurrly/server/swagger/Reader.java rename to src/main/java/com/wurrly/server/swagger/Reader.java index e16ed4b..9f32c61 100644 --- a/src/com/wurrly/server/swagger/Reader.java +++ b/src/main/java/com/wurrly/server/swagger/Reader.java @@ -122,18 +122,15 @@ public Swagger getSwagger() { * @return the generated Swagger definition */ public Swagger read(Set> classes) { - Set> sortedClasses = new TreeSet>(new Comparator>() { - @Override - public int compare(Class class1, Class class2) { - if (class1.equals(class2)) { - return 0; - } else if (class1.isAssignableFrom(class2)) { - return -1; - } else if (class2.isAssignableFrom(class1)) { - return 1; - } - return class1.getName().compareTo(class2.getName()); - } + Set> sortedClasses = new TreeSet<>((class1, class2) -> { + if (class1.equals(class2)) { + return 0; + } else if (class1.isAssignableFrom(class2)) { + return -1; + } else if (class2.isAssignableFrom(class1)) { + return 1; + } + return class1.getName().compareTo(class2.getName()); }); sortedClasses.addAll(classes); @@ -166,7 +163,7 @@ public int compare(Class class1, Class class2) { } for (Class cls : sortedClasses) { - read(cls, "", null, false, new String[0], new String[0], new LinkedHashMap(), new ArrayList(), new HashSet>()); + read(cls, "", null, false, new String[0], new String[0], new LinkedHashMap(), new ArrayList(), new HashSet<>()); } // for (ReaderListener listener : listeners.values()) { @@ -189,11 +186,11 @@ public Swagger read(Class cls) { readSwaggerConfig(cls, swaggerDefinition); } - return read(cls, "", null, false, new String[0], new String[0], new LinkedHashMap(), new ArrayList(), new HashSet>()); + return read(cls, "", null, false, new String[0], new String[0], new LinkedHashMap(), new ArrayList(), new HashSet<>()); } protected Swagger read(Class cls, String parentPath, String parentMethod, boolean isSubresource, String[] parentConsumes, String[] parentProduces, Map parentTags, List parentParameters) { - return read(cls, parentPath, parentMethod, isSubresource, parentConsumes, parentProduces, parentTags, parentParameters, new HashSet>()); + return read(cls, parentPath, parentMethod, isSubresource, parentConsumes, parentProduces, parentTags, parentParameters, new HashSet<>()); } private Swagger read(Class cls, String parentPath, String parentMethod, boolean isSubresource, String[] parentConsumes, String[] parentProduces, Map parentTags, List parentParameters, Set> scannedResources) { @@ -224,9 +221,8 @@ private Swagger read(Class cls, String parentPath, String parentMethod, boole } // api readable only if @Api present; cannot be hidden because checked in classReadable. - boolean apiReadable = hasApiAnnotation; - if (apiReadable) { + if (hasApiAnnotation) { // the value will be used as a tag for 2.0 UNLESS a Tags annotation is present Set tagStrings = extractTags(api); for (String tagString : tagStrings) { @@ -304,7 +300,7 @@ private Swagger read(Class cls, String parentPath, String parentMethod, boole javax.ws.rs.Path methodPath = ReflectionUtils.getAnnotation(method, javax.ws.rs.Path.class); String operationPath = getPath(apiPath, methodPath, parentPath); - Map regexMap = new LinkedHashMap(); + Map regexMap = new LinkedHashMap<>(); operationPath = PathUtils.parsePath(operationPath, regexMap); if (operationPath != null) { if (isIgnored(operationPath)) { @@ -348,8 +344,8 @@ private Swagger read(Class cls, String parentPath, String parentMethod, boole String[] apiConsumes = consumes; if (parentConsumes != null) { - Set both = new LinkedHashSet(Arrays.asList(apiConsumes)); - both.addAll(new LinkedHashSet(Arrays.asList(parentConsumes))); + Set both = new LinkedHashSet<>(Arrays.asList(apiConsumes)); + both.addAll(new LinkedHashSet<>(Arrays.asList(parentConsumes))); if (operation.getConsumes() != null) { both.addAll(new LinkedHashSet(operation.getConsumes())); } @@ -358,8 +354,8 @@ private Swagger read(Class cls, String parentPath, String parentMethod, boole String[] apiProduces = produces; if (parentProduces != null) { - Set both = new LinkedHashSet(Arrays.asList(apiProduces)); - both.addAll(new LinkedHashSet(Arrays.asList(parentProduces))); + Set both = new LinkedHashSet<>(Arrays.asList(apiProduces)); + both.addAll(new LinkedHashSet<>(Arrays.asList(parentProduces))); if (operation.getProduces() != null) { both.addAll(new LinkedHashSet(operation.getProduces())); } @@ -471,7 +467,7 @@ protected Parameter readImplicitParam(ApiImplicitParam param) { return null; } final Type type = ReflectionUtils.typeFromString(param.dataType()); - return ParameterProcessor.applyAnnotations(swagger, p, (type == null) ? String.class : type, + return ParameterProcessor.applyAnnotations(swagger, p, (type == null) ? String.class : type, Arrays.asList(param)); } @@ -706,7 +702,7 @@ private static Class getClassArgument(Type cls) { } protected Set extractTags(Api api) { - Set output = new LinkedHashSet(); + Set output = new LinkedHashSet<>(); boolean hasExplicitTags = false; for (String tag : api.tags()) { @@ -808,7 +804,7 @@ private Operation parseMethod(Class cls, Method method, AnnotatedMethod annot ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class); - String operationId = null; + String operationId; // check if it's an inherited or implemented method. boolean methodInSuperType = false; if (!cls.isInterface()) { @@ -926,7 +922,7 @@ private Operation parseMethod(Class cls, Method method, AnnotatedMethod annot } } - List apiResponses = new ArrayList(); + List apiResponses = new ArrayList<>(); if (responseAnnotation != null) { apiResponses.addAll(Arrays.asList(responseAnnotation.value())); } @@ -1065,7 +1061,7 @@ private List getParameters(Type type, List annotations, j LOGGER.debug("getParameters for {}", type); - Set typesToSkip = new HashSet(); + Set typesToSkip = new HashSet<>(); // typesToSkip.add(ServerRequest.class); final SwaggerExtension extension = chain.next(); @@ -1098,6 +1094,9 @@ private List getParameters(Type type, List annotations, j LOGGER.debug("getParameters for {}", type); if (ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations) != null) { + + LOGGER.info(parameter.getDescription() + " -> " + type); + processed.add(parameter); } } diff --git a/src/com/wurrly/server/swagger/ServerParameterExtension.java b/src/main/java/com/wurrly/server/swagger/ServerParameterExtension.java similarity index 95% rename from src/com/wurrly/server/swagger/ServerParameterExtension.java rename to src/main/java/com/wurrly/server/swagger/ServerParameterExtension.java index 8f34afa..5856806 100644 --- a/src/com/wurrly/server/swagger/ServerParameterExtension.java +++ b/src/main/java/com/wurrly/server/swagger/ServerParameterExtension.java @@ -72,10 +72,8 @@ protected JavaType constructType(Type type) type = java.io.File.class; } - - JavaType newType = super.constructType(type); - - return newType; + + return super.constructType(type); } diff --git a/src/com/wurrly/services/ConfigurableService.java b/src/main/java/com/wurrly/services/ConfigurableService.java similarity index 100% rename from src/com/wurrly/services/ConfigurableService.java rename to src/main/java/com/wurrly/services/ConfigurableService.java diff --git a/src/com/wurrly/services/SwaggerService.java b/src/main/java/com/wurrly/services/SwaggerService.java similarity index 93% rename from src/com/wurrly/services/SwaggerService.java rename to src/main/java/com/wurrly/services/SwaggerService.java index 0be8445..e403d20 100644 --- a/src/com/wurrly/services/SwaggerService.java +++ b/src/main/java/com/wurrly/services/SwaggerService.java @@ -52,9 +52,9 @@ public class SwaggerService extends ConfigurableService implements Supplier { - - this.reader.read(c); - - }); + classes.forEach( c -> this.reader.read(c)); this.swagger = this.reader.getSwagger(); @@ -196,7 +192,7 @@ public void generateSwaggerHTML() { PebbleEngine engine = new PebbleEngine.Builder().build(); - PebbleTemplate compiledTemplate = engine.getTemplate("resources/swagger/index.html"); + PebbleTemplate compiledTemplate = engine.getTemplate("swagger/index.html"); String themePath = "swagger-ui.css"; @@ -263,7 +259,7 @@ public void handleRequest(HttpServerExchange exchange) throws Exception public void handleRequest(HttpServerExchange exchange) throws Exception { - + exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ContentType.HTML.getMimeType()); exchange.getResponseSender().send(swaggerIndexHTML); @@ -288,6 +284,7 @@ public void handleRequest(HttpServerExchange exchange) throws Exception canonicalPath = swaggerThemesPath + canonicalPath.split(swaggerBasePath+"/themes")[1]; exchange.setRelativePath(canonicalPath); + log.info("path: " + canonicalPath); super.handleRequest(exchange); @@ -301,8 +298,12 @@ public void handleRequest(HttpServerExchange exchange) throws Exception try { - //Resource swaggerUIResource = resourceManager.getResource(webJarPath); + Resource swaggerUIResource = resourceManager.getResource("./swagger/index.html"); + log.info("swaggerUIResource: " + swaggerUIResource); + log.info("swaggerUIResource: " + swaggerUIResource.getPath()); + log.info("swaggerUIResource: " + swaggerUIResource.getFilePath()); + pathTemplate = this.swaggerBasePath + "/*"; router.add(HttpMethod.GET, pathTemplate, new ResourceHandler(resourceManager){ @@ -310,11 +311,12 @@ public void handleRequest(HttpServerExchange exchange) throws Exception @Override public void handleRequest(HttpServerExchange exchange) throws Exception { - + String canonicalPath = CanonicalPathUtils.canonicalize((exchange.getRelativePath())); canonicalPath = swaggerResourcePath + canonicalPath.split(swaggerBasePath)[1]; + log.info("path: " + canonicalPath); exchange.setRelativePath(canonicalPath); super.handleRequest(exchange); diff --git a/src/com/wurrly/tests/TestInvoker.java b/src/main/java/com/wurrly/tests/TestInvoker.java similarity index 98% rename from src/com/wurrly/tests/TestInvoker.java rename to src/main/java/com/wurrly/tests/TestInvoker.java index e903a73..35a5ee0 100644 --- a/src/com/wurrly/tests/TestInvoker.java +++ b/src/main/java/com/wurrly/tests/TestInvoker.java @@ -120,7 +120,7 @@ public static void main(String[] args) System.out.println("consumer: " + consumer); - consumer.accept( users, new ServerRequest(), 2501l, Optional.of("default")); + consumer.accept( users, new ServerRequest(), 2501L, Optional.of("default")); } @@ -180,7 +180,7 @@ public static void invokeMethodHandler(Object source,MethodHandle handle) { try { - handle.bindTo(source).invokeWithArguments(new ServerRequest(), 2501l, Optional.of("default")); + handle.bindTo(source).invokeWithArguments(new ServerRequest(), 2501L, Optional.of("default")); } catch ( Throwable e) { diff --git a/src/com/wurrly/utilities/ChunkedStream.java b/src/main/java/com/wurrly/utilities/ChunkedStream.java similarity index 100% rename from src/com/wurrly/utilities/ChunkedStream.java rename to src/main/java/com/wurrly/utilities/ChunkedStream.java diff --git a/src/com/wurrly/utilities/JsonMapper.java b/src/main/java/com/wurrly/utilities/JsonMapper.java similarity index 97% rename from src/com/wurrly/utilities/JsonMapper.java rename to src/main/java/com/wurrly/utilities/JsonMapper.java index a5e7ad7..bde7522 100644 --- a/src/com/wurrly/utilities/JsonMapper.java +++ b/src/main/java/com/wurrly/utilities/JsonMapper.java @@ -154,10 +154,8 @@ public static JsonNode toJSON(Class view, Object object) } final String jsonString = writer.writeValueAsString(object); - - final JsonNode node = getInstance().readTree(jsonString); - - return node; + + return getInstance().readTree(jsonString); } catch(Exception e) { Logger.error("\n" + e.getMessage() + "\nobject: " + object.getClass().getSimpleName(),e); @@ -202,7 +200,7 @@ public static ObjectNode wrap(String name, Class view, Object object) WRITER_CACHE.put(view, writer); } - JsonNode objectNode = null; + JsonNode objectNode; if (object instanceof List) { @@ -275,12 +273,9 @@ public static JsonNode withJSONView(Class view, Object object) final String jsonString = writer.writeValueAsString(object); - - - final JsonNode node = getInstance().readTree(jsonString); - - - return node; + + + return getInstance().readTree(jsonString); } catch(Exception e) { Logger.error(e.getMessage() + "\nobject: " + object.getClass().getSimpleName(),e); @@ -364,7 +359,7 @@ public static ObjectNode wrapJSONView(String name, Class view, Object object { ObjectWriter writer = WRITER_CACHE.get(view); ObjectNode resultNode = getInstance().createObjectNode(); - JsonNode objectNode = null; + JsonNode objectNode; try { @@ -427,7 +422,7 @@ public static JsonNode stringCollectionToJSONArray(Collection elements) try{ array.add( JsonMapper.getInstance().readTree(element) ); } - catch(Exception e) + catch(Exception ignored) { } }); @@ -446,7 +441,7 @@ public static Set toStringSet(Collection elements) { stringSet.add( JsonMapper.toJSONString(element) ); } - catch(Exception e) + catch(Exception ignored) { } }); diff --git a/src/com/wurrly/utilities/ReapableQueue.java b/src/main/java/com/wurrly/utilities/ReapableQueue.java similarity index 98% rename from src/com/wurrly/utilities/ReapableQueue.java rename to src/main/java/com/wurrly/utilities/ReapableQueue.java index aedc091..e002d25 100644 --- a/src/com/wurrly/utilities/ReapableQueue.java +++ b/src/main/java/com/wurrly/utilities/ReapableQueue.java @@ -137,7 +137,7 @@ public boolean add(T value) { if (ended.get() != 0) return false; - Node new_tail = new Node(value); + Node new_tail = new Node<>(value); Node old_tail = tail_updater.getAndSet(this, new_tail); if (null != old_tail) { // if reaped right now, then do not set_next(...) @@ -229,7 +229,7 @@ public Reaped reap(final boolean is_last_reap) throws ReapException { if (is_last_reap) ended.compareAndSet(2, 3); - return new Reaped(old_head, old_tail); + return new Reaped<>(old_head, old_tail); } else { diff --git a/src/com/wurrly/utilities/SecurityOps.java b/src/main/java/com/wurrly/utilities/SecurityOps.java similarity index 100% rename from src/com/wurrly/utilities/SecurityOps.java rename to src/main/java/com/wurrly/utilities/SecurityOps.java diff --git a/src/resources/META-INF/services/com.wurrly.server.swagger.ServerExtension b/src/main/resources/META-INF/services/com.wurrly.server.swagger.ServerExtension similarity index 100% rename from src/resources/META-INF/services/com.wurrly.server.swagger.ServerExtension rename to src/main/resources/META-INF/services/com.wurrly.server.swagger.ServerExtension diff --git a/src/resources/META-INF/services/com.wurrly.server.swagger.ServerModelResolver b/src/main/resources/META-INF/services/com.wurrly.server.swagger.ServerModelResolver similarity index 100% rename from src/resources/META-INF/services/com.wurrly.server.swagger.ServerModelResolver rename to src/main/resources/META-INF/services/com.wurrly.server.swagger.ServerModelResolver diff --git a/src/resources/swagger/index.html b/src/main/resources/swagger/index.html similarity index 98% rename from src/resources/swagger/index.html rename to src/main/resources/swagger/index.html index 2bd505b..cff9601 100644 --- a/src/resources/swagger/index.html +++ b/src/main/resources/swagger/index.html @@ -74,11 +74,15 @@