|
| 1 | +package io.springside.springtime.jetty; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.util.Map; |
| 5 | +import java.util.Map.Entry; |
| 6 | + |
| 7 | +import javax.servlet.ServletException; |
| 8 | +import javax.servlet.http.HttpServletRequest; |
| 9 | +import javax.servlet.http.HttpServletResponse; |
| 10 | + |
| 11 | +import org.eclipse.jetty.server.Request; |
| 12 | +import org.eclipse.jetty.server.handler.AbstractHandler; |
| 13 | +import org.springframework.context.ApplicationContext; |
| 14 | + |
| 15 | +import io.springside.springtime.serializer.JsonSerializer; |
| 16 | +import io.springside.springtime.serializer.Serializer; |
| 17 | +import io.springside.springtime.service.ServiceDispatcher; |
| 18 | +import io.springside.springtime.service.ServiceBeanRegistry; |
| 19 | +import io.swagger.annotations.Api; |
| 20 | + |
| 21 | +/** |
| 22 | + * Jetty的Handler. |
| 23 | + * |
| 24 | + * 以服务化框架的方式直接处理/rpc 路径的请求. |
| 25 | + * 其他路径的请求,仍然交给WebServletContxt Handler处理. |
| 26 | + */ |
| 27 | +public class SpringTimeHandler extends AbstractHandler { |
| 28 | + |
| 29 | + public static final String RPC_PREFIX = "/rpc"; |
| 30 | + |
| 31 | + private ServiceDispatcher dispatcher; |
| 32 | + private Serializer serializer = new JsonSerializer(); |
| 33 | + |
| 34 | + public SpringTimeHandler(ApplicationContext applicationContext) { |
| 35 | + ServiceBeanRegistry serviceRegistry = new ServiceBeanRegistry(); |
| 36 | + Map<String, Object> beans = applicationContext.getBeansWithAnnotation(Api.class); |
| 37 | + for (Entry<String, Object> entry : beans.entrySet()) { |
| 38 | + serviceRegistry.add(RPC_PREFIX, entry.getKey(), entry.getValue()); |
| 39 | + } |
| 40 | + |
| 41 | + dispatcher = new ServiceDispatcher(serviceRegistry); |
| 42 | + } |
| 43 | + |
| 44 | + @Override |
| 45 | + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) |
| 46 | + throws IOException, ServletException { |
| 47 | + if (!target.startsWith(RPC_PREFIX)) { |
| 48 | + return; |
| 49 | + } |
| 50 | + String path = target.toLowerCase(); |
| 51 | + Serializer serializerForRequest = serializer; |
| 52 | + |
| 53 | + dispatcher.dispatch(path, serializerForRequest, baseRequest.getInputStream(), response.getOutputStream()); |
| 54 | + |
| 55 | + response.setContentType(Serializer.JSON_TYPE); |
| 56 | + response.setStatus(HttpServletResponse.SC_OK); |
| 57 | + response.getOutputStream().flush(); |
| 58 | + baseRequest.setHandled(true); |
| 59 | + } |
| 60 | +} |
0 commit comments