Skip to content

Commit

Permalink
Cleanup asset and swagger resource handling.
Browse files Browse the repository at this point in the history
  • Loading branch information
noboomu committed May 2, 2017
1 parent 8821dc8 commit cab3828
Show file tree
Hide file tree
Showing 5 changed files with 102 additions and 63 deletions.
59 changes: 27 additions & 32 deletions src/main/java/io/sinistral/proteus/modules/ServerModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,9 @@

/**
* @author jbauer
*
*/
@Singleton
public class ServerModule extends AbstractModule
public class ServerModule extends AbstractModule
{
private static Logger log = LoggerFactory.getLogger(ServerModule.class.getCanonicalName());

Expand All @@ -42,24 +41,21 @@ public class ServerModule extends AbstractModule
protected Set<Class<? extends Service>> registeredServices = new HashSet<>();

protected Config config;

public ServerModule(Config config)
{
this.config = config;
}



@SuppressWarnings("unchecked")
@Override
protected void configure()
{



this.binder().requestInjection(this);



RoutingHandler router = new RoutingHandler();

try
{
String className = config.getString("application.fallbackHandler");
Expand All @@ -68,41 +64,40 @@ protected void configure()
router.setFallbackHandler(clazz.newInstance());
} catch (Exception e)
{
log.error(e.getMessage(),e);
log.error(e.getMessage(), e);
}
this.bind(RoutingHandler.class).toInstance(router);

this.bind(RoutingHandler.class).toInstance(router);

this.bind(ServerModule.class).toInstance(this);



try
{
String className = config.getString("application.defaultResponseListener");
log.info("Installing DefaultResponseListener " + className);
log.info("Installing DefaultResponseListener " + className);
Class<? extends DefaultResponseListener> clazz = (Class<? extends DefaultResponseListener>) Class.forName(className);
this.bind(DefaultResponseListener.class).to(clazz).in(Singleton.class);
this.bind(DefaultResponseListener.class).to(clazz).in(Singleton.class);
} catch (Exception e)
{
log.error(e.getMessage(),e);
log.error(e.getMessage(), e);
}



this.bind(new TypeLiteral<Set<Class<?>>>() {}).annotatedWith(Names.named("registeredControllers")).toInstance(registeredControllers);
this.bind(new TypeLiteral<Set<EndpointInfo>>() {}).annotatedWith(Names.named("registeredEndpoints")).toInstance(registeredEndpoints);
this.bind(new TypeLiteral<Set<Class<? extends Service>>>() {}).annotatedWith(Names.named("registeredServices")).toInstance(registeredServices);

this.bind(XmlMapper.class).toInstance(new XmlMapper());


this.bind(new TypeLiteral<Set<Class<?>>>()
{
}).annotatedWith(Names.named("registeredControllers")).toInstance(registeredControllers);
this.bind(new TypeLiteral<Set<EndpointInfo>>()
{
}).annotatedWith(Names.named("registeredEndpoints")).toInstance(registeredEndpoints);
this.bind(new TypeLiteral<Set<Class<? extends Service>>>()
{
}).annotatedWith(Names.named("registeredServices")).toInstance(registeredServices);

this.bind(XmlMapper.class).toInstance(new XmlMapper());

JsonIterator.setMode(DecodingMode.DYNAMIC_MODE_AND_MATCH_FIELD_WITH_HASH);
JsonStream.setMode(EncodingMode.DYNAMIC_MODE);
JsoniterAnnotationSupport.enable();


}




}
6 changes: 4 additions & 2 deletions src/main/java/io/sinistral/proteus/server/swagger/Reader.java
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
import io.swagger.util.ParameterProcessor;
import io.swagger.util.PathUtils;
import io.swagger.util.ReflectionUtils;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;

/**
Expand Down Expand Up @@ -1022,7 +1023,7 @@ else if( responseCls.isAssignableFrom(CompletableFuture.class) )

}

if(type.equals(ServerRequest.class) || type.equals(HttpServerExchange.class) || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse"))
if(type.equals(ServerRequest.class) || type.equals(HttpServerExchange.class) || type.equals(HttpHandler.class) || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse"))
{
continue;
}
Expand All @@ -1038,7 +1039,7 @@ else if( responseCls.isAssignableFrom(CompletableFuture.class) )
for (int i = 0; i < annotatedMethod.getParameterCount(); i++) {
AnnotatedParameter param = annotatedMethod.getParameter(i);

if(param.getParameterType().equals(ServerRequest.class) || param.getParameterType().equals(HttpServerExchange.class) || param.getParameterType().getTypeName().contains("ServerResponse"))
if(param.getParameterType().equals(ServerRequest.class) || param.getParameterType().equals(HttpServerExchange.class) || param.getParameterType().equals(HttpHandler.class)|| param.getParameterType().getTypeName().contains("ServerResponse"))
{
continue;
}
Expand Down Expand Up @@ -1114,6 +1115,7 @@ private List<Parameter> getParameters(Type type, List<Annotation> annotations, j
typesToSkip.add(TypeFactory.defaultInstance().constructType(ServerRequest.class));
typesToSkip.add(TypeFactory.defaultInstance().constructType(HttpServerExchange.class));
typesToSkip.add(TypeFactory.defaultInstance().constructType(ServerResponse.class));
typesToSkip.add(TypeFactory.defaultInstance().constructType(HttpHandler.class));

final SwaggerExtension extension = chain.next();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public List<Parameter> extractParameters(List<Annotation> annotations, Type type
protected boolean shouldIgnoreType(Type type, Set<Type> typesToSkip)
{

if( type.getTypeName().contains("io.sinistral.proteus.server.ServerRequest") || type.getTypeName().contains("HttpServerExchange") || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse"))
if( type.getTypeName().contains("io.sinistral.proteus.server.ServerRequest") || type.getTypeName().contains("HttpServerExchange") || type.getTypeName().contains("HttpHandler") || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse"))
{
return true;
}
Expand Down
26 changes: 17 additions & 9 deletions src/main/java/io/sinistral/proteus/services/AssetsService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import java.nio.file.Paths;
import java.util.Set;
import java.util.function.Supplier;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -24,7 +25,7 @@
* @author jbauer
*
*/
public class AssetsService extends BaseService
public class AssetsService extends BaseService implements Supplier<RoutingHandler>
{
private static Logger log = LoggerFactory.getLogger(AssetsService.class.getCanonicalName());

Expand All @@ -45,27 +46,34 @@ public class AssetsService extends BaseService
public AssetsService()
{
}


@Override
protected void startUp() throws Exception
{
super.startUp();


public RoutingHandler get()
{
RoutingHandler router = new RoutingHandler();

final String assetsPath = serviceConfig.getString("path");
final String assetsDirectoryName = serviceConfig.getString("dir") ;
final Integer assetsCacheTime = serviceConfig.getInt("cache.time");

final FileResourceManager fileResourceManager = new FileResourceManager(Paths.get(assetsDirectoryName).toFile());


router.add(Methods.GET, assetsPath + "/*", io.undertow.Handlers.rewrite("regex('" + assetsPath + "/(.*)')", "/$1", getClass().getClassLoader(), new ResourceHandler(fileResourceManager)
.setCachable(TruePredicate.instance())
.setCacheTime(assetsCacheTime)
));

this.registeredEndpoints.add(EndpointInfo.builder().withConsumes("*/*").withProduces("*/*").withPathTemplate(assetsPath).withControllerName("Assets").withMethod(Methods.GET).build());

return router;
}


@Override
protected void startUp() throws Exception
{
super.startUp();

router.addAll(this.get());
}


Expand Down
72 changes: 53 additions & 19 deletions src/main/java/io/sinistral/proteus/services/SwaggerService.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@

package io.sinistral.proteus.services;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;

import javax.ws.rs.HttpMethod;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -35,6 +39,7 @@
import io.undertow.server.HttpServerExchange;
import io.undertow.server.RoutingHandler;
import io.undertow.server.handlers.resource.ClassPathResourceManager;
import io.undertow.server.handlers.resource.Resource;
import io.undertow.server.handlers.resource.ResourceHandler;
import io.undertow.util.CanonicalPathUtils;
import io.undertow.util.Headers;
Expand All @@ -48,9 +53,9 @@ public class SwaggerService extends BaseService implements Supplier<RoutingHan

protected io.sinistral.proteus.server.swagger.Reader reader = null;

protected final String swaggerResourcePath = "./swagger";
protected final String swaggerResourcePath = "swagger";

protected final String swaggerThemesPath = "./swagger/themes";
protected final String swaggerThemesPath = "swagger/themes";

protected Swagger swagger = null;

Expand Down Expand Up @@ -107,6 +112,8 @@ public class SwaggerService extends BaseService implements Supplier<RoutingHan

protected ObjectWriter writer = null;

protected ClassLoader serviceClassLoader = null;

/**
* @param config
*/
Expand Down Expand Up @@ -211,10 +218,11 @@ public void generateSwaggerHTML()
try
{


// PebbleEngine engine = new PebbleEngine.Builder().build();

byte[] templateBytes = Files.readAllBytes(Paths.get(this.getClass().getClassLoader().getResource("swagger/index.html").toURI()));
this.serviceClassLoader = this.getClass().getClassLoader();

final InputStream templateInputStream = this.getClass().getClassLoader().getResourceAsStream("swagger/index.html");

byte[] templateBytes = IOUtils.toByteArray(templateInputStream);

String templateString = new String(templateBytes,Charset.defaultCharset());

Expand All @@ -231,6 +239,19 @@ public void generateSwaggerHTML()
templateString = templateString.replaceAll("\\{\\{ swaggerFullPath \\}\\}","//" + host + ((port != 80 && port != 443) ? ":" + port : "") + this.swaggerBasePath + ".json");

this.swaggerIndexHTML = templateString;


// final InputStream resourceInputStream = this.getClass().getClassLoader().getResourceAsStream("swagger/swagger-ui-bundle.js");
//
// byte[] resourceBytes = IOUtils.toByteArray(resourceInputStream);
//
// String resourceString = new String(resourceBytes,Charset.defaultCharset());
//
// System.out.println("resource: " + resourceString);
//




} catch (Exception e)
{
Expand Down Expand Up @@ -283,11 +304,9 @@ public void handleRequest(HttpServerExchange exchange) throws Exception

this.registeredEndpoints.add(EndpointInfo.builder().withConsumes("*/*").withProduces("text/html").withPathTemplate(pathTemplate).withControllerName("Swagger").withMethod(Methods.GET).build());

ClassPathResourceManager resourceManager = new ClassPathResourceManager(this.getClass().getClassLoader());

pathTemplate = this.swaggerBasePath + "/themes/*";

router.add(HttpMethod.GET, pathTemplate, new ResourceHandler(resourceManager){
router.add(HttpMethod.GET, pathTemplate, new HttpHandler(){

@Override
public void handleRequest(HttpServerExchange exchange) throws Exception
Expand All @@ -297,10 +316,16 @@ public void handleRequest(HttpServerExchange exchange) throws Exception

canonicalPath = swaggerThemesPath + canonicalPath.split(swaggerBasePath+"/themes")[1];

exchange.setRelativePath(canonicalPath);

super.handleRequest(exchange);
try(final InputStream resourceInputStream = serviceClassLoader.getResourceAsStream(canonicalPath))
{

byte[] resourceBytes = IOUtils.toByteArray(resourceInputStream);

exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, io.sinistral.proteus.server.MediaType.TEXT_CSS_UTF8.toString());

exchange.getResponseSender().send(ByteBuffer.wrap(resourceBytes));

}
}

});
Expand All @@ -315,19 +340,28 @@ public void handleRequest(HttpServerExchange exchange) throws Exception

pathTemplate = this.swaggerBasePath + "/*";

router.add(HttpMethod.GET, pathTemplate, new ResourceHandler(resourceManager){
router.add(HttpMethod.GET, pathTemplate, new HttpHandler(){

@Override
public void handleRequest(HttpServerExchange exchange) throws Exception
{

String canonicalPath = CanonicalPathUtils.canonicalize((exchange.getRelativePath()));
canonicalPath = swaggerResourcePath + canonicalPath.split(swaggerBasePath)[1];

exchange.setRelativePath(canonicalPath);

super.handleRequest(exchange);
System.out.println("canonicalPath: " + canonicalPath);

try(final InputStream resourceInputStream = serviceClassLoader.getResourceAsStream(canonicalPath))
{

byte[] resourceBytes = IOUtils.toByteArray(resourceInputStream);

exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, io.sinistral.proteus.server.MediaType.APPLICATION_JAVASCRIPT_UTF8.toString());

exchange.getResponseSender().send(ByteBuffer.wrap(resourceBytes));

}

}

Expand Down

0 comments on commit cab3828

Please sign in to comment.