PageRenderTime 47ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/xjt/ws/core/ServiceInvokeServlet.java

https://bitbucket.org/xiejuntao/xdesktop
Java | 255 lines | 183 code | 15 blank | 57 comment | 28 complexity | 3d3a753deb78fdcd04d1eddcc8d84dd6 MD5 | raw file
  1. package xjt.ws.core;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.PrintWriter;
  5. import java.net.URLEncoder;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. import javax.servlet.ServletConfig;
  9. import javax.servlet.ServletException;
  10. import javax.servlet.ServletOutputStream;
  11. import javax.servlet.http.HttpServlet;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14. import org.apache.commons.io.IOUtils;
  15. import org.apache.commons.lang.StringUtils;
  16. import org.slf4j.Logger;
  17. import org.slf4j.LoggerFactory;
  18. import org.springframework.web.context.WebApplicationContext;
  19. import org.springframework.web.context.support.WebApplicationContextUtils;
  20. import org.springframework.web.multipart.MultipartException;
  21. import org.springframework.web.multipart.MultipartFile;
  22. import org.springframework.web.multipart.MultipartHttpServletRequest;
  23. import org.springframework.web.multipart.commons.CommonsMultipartResolver;
  24. import xjt.ws.invoker.ServiceInvoker;
  25. import com.alibaba.fastjson.JSON;
  26. import com.alibaba.fastjson.JSONObject;
  27. /**
  28. * Web服务调用的Servlet入口<br>
  29. * @author huzq
  30. * @author xjt
  31. */
  32. public class ServiceInvokeServlet extends HttpServlet {
  33. private static final long serialVersionUID = 1L;
  34. private static final Logger logger = LoggerFactory.getLogger(ServiceInvokeServlet.class);
  35. private ServiceInvoker serviceInvoker;
  36. private String encoding = "utf-8";
  37. public void init(ServletConfig config) throws ServletException {
  38. super.init(config);
  39. initServiceInvoker();
  40. }
  41. /*
  42. *调用指定服务名的服务方法
  43. */
  44. protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  45. req.setCharacterEncoding(encoding);
  46. logger.debug("请求编码:"+req.getCharacterEncoding());
  47. ServiceRequest serviceRequest = buildServiceRequest(req, resp);
  48. logger.debug("调用服务:" + serviceRequest);
  49. ServiceResponse serviceResponse = new ServiceResponse();
  50. try {
  51. this.serviceInvoker.invoke(serviceRequest,serviceResponse);
  52. }catch (Throwable t) {
  53. while(t.getCause()!=null){
  54. t = t.getCause();
  55. }
  56. logger.error("服务异常:", t);
  57. serviceResponse.setErrorInfo(t);
  58. }
  59. if(serviceResponse.isCached()){
  60. resp.reset();
  61. resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
  62. }else if (serviceResponse.isBinary()) {
  63. printBinary(resp, serviceResponse);
  64. } else {
  65. if (serviceResponse.isSuccess()) {
  66. printSuccess(resp, serviceResponse.getResults(),serviceResponse.getLastModifiedTime());
  67. } else {
  68. printError(resp, serviceResponse.getErrors(), serviceResponse.getErrorDetails());
  69. }
  70. }
  71. }
  72. /**
  73. * 输出二进制数据
  74. *
  75. * @param resp
  76. * @param serviceResp
  77. * @throws IOException
  78. */
  79. private void printBinary(HttpServletResponse resp, ServiceResponse serviceResp) throws IOException {
  80. resp.reset();
  81. ResponseFile file = serviceResp.getResponseFile();
  82. if (file == null) {
  83. printError(resp, "服务返回的文件流为空");
  84. return;
  85. }
  86. String fileName = file.getFileName();
  87. if (StringUtils.isNotEmpty(fileName)) {
  88. fileName = URLEncoder.encode(fileName,this.encoding);
  89. logger.debug("filename:"+fileName);
  90. resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
  91. resp.setHeader(ServiceResponse.RESPONSE_HEADER_FILE_NAME, fileName);
  92. }
  93. if (file.getLength() > 0) {
  94. resp.setContentLength((int)file.getLength());
  95. resp.setHeader(ServiceResponse.RESPONSE_HEADER_FILE_SIZE, file.getLength()+"");
  96. }
  97. if (serviceResp.getLastModifiedTime()!=null){
  98. resp.setHeader(ServiceResponse.RESPONSE_HEADER_LAST_MODIFIED_TIME, serviceResp.getLastModifiedTime());
  99. }else if (file.getLastModifiedTime() > 0) {
  100. resp.setHeader(ServiceResponse.RESPONSE_HEADER_LAST_MODIFIED_TIME, file.getLastModifiedTime() + "");
  101. }
  102. if(file.getPages()!=null){
  103. resp.setHeader(ServiceResponse.RESPONSE_HEADER_PAGES, file.getPages()+"");
  104. }
  105. resp.setContentType("application/octet-stream;charset="+encoding);
  106. if (file.getInputStream() != null) {
  107. ServletOutputStream os = null;
  108. InputStream is = null;
  109. try{
  110. is = file.getInputStream();
  111. os = resp.getOutputStream();
  112. IOUtils.copy(is, os);
  113. }finally{
  114. if(is!=null) {
  115. is.close();
  116. }
  117. if(os!=null){
  118. os.close();
  119. }
  120. }
  121. } else {
  122. printError(resp, "服务返回的文件流为空");
  123. }
  124. resp.flushBuffer();
  125. }
  126. /**
  127. * 输出成功的结果
  128. *
  129. * @param resp
  130. * @param results
  131. * @throws IOException
  132. */
  133. private void printSuccess(HttpServletResponse resp, Object results,String lastModifedTime) throws IOException {
  134. printText(resp, true, results, null, null,lastModifedTime);
  135. }
  136. /**
  137. * 输出错误信息
  138. *
  139. * @param resp
  140. * @param errors
  141. * @throws IOException
  142. */
  143. private void printError(HttpServletResponse resp, String errors) throws IOException {
  144. printText(resp, false, null, errors, null,null);
  145. }
  146. /**
  147. * 输出错误信息
  148. *
  149. * @param resp
  150. * @param errors
  151. * @param errorDetails
  152. * @throws IOException
  153. */
  154. private void printError(HttpServletResponse resp, String errors, String errorDetails) throws IOException {
  155. printText(resp, false, null, errors, errorDetails,null);
  156. }
  157. /**
  158. * 输出文本信息
  159. *
  160. * @param resp
  161. * @param results
  162. * @param success
  163. * @throws IOException
  164. */
  165. private void printText(HttpServletResponse resp, boolean success, Object results, String errors, String errorDetails,String lastModifiedTime)
  166. throws IOException {
  167. resp.reset();
  168. HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
  169. if (success) {
  170. resp.setStatus(HttpServletResponse.SC_OK);
  171. if (results != null) {
  172. resultMap.put(ServiceResponse.RESULTS_PARAM_RESULTS, results);
  173. }
  174. } else {
  175. resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  176. resultMap.put(ServiceResponse.RESULTS_PARAM_ERRORS, errors);
  177. resultMap.put(ServiceResponse.RESULT_PARAM_ERROR_DETAILS, errorDetails);
  178. }
  179. resp.setContentType("application/json;charset="+encoding);
  180. if(lastModifiedTime!=null){
  181. resp.setHeader(ServiceResponse.RESPONSE_HEADER_LAST_MODIFIED_TIME, lastModifiedTime);
  182. }
  183. PrintWriter out = resp.getWriter();
  184. out.print(JSON.toJSONString(resultMap));
  185. resp.flushBuffer();
  186. out.close();
  187. }
  188. /**
  189. * 构造服务请求
  190. *
  191. * @param req
  192. * @param resp
  193. * @return
  194. * @throws MultipartException
  195. * @throws IOException
  196. * @throws ServletException
  197. */
  198. private ServiceRequest buildServiceRequest(HttpServletRequest req, HttpServletResponse resp)
  199. throws MultipartException, IOException, ServletException {
  200. CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(getServletContext());
  201. boolean isMultiPart = multipartResolver.isMultipart(req);
  202. logger.debug("multipart:" + isMultiPart);
  203. //MultipartFile[] files = null;
  204. Map<String,MultipartFile> fileMap = null;
  205. if (isMultiPart) {
  206. MultipartHttpServletRequest request = multipartResolver.resolveMultipart(req);
  207. fileMap = request.getFileMap();
  208. //files = (MultipartFile[]) fileMap.values().toArray(new MultipartFile[0]);
  209. req = request;
  210. }
  211. String service = StringUtils.trim(req.getParameter(ServiceRequest.POST_PARAM_SERVICE));
  212. if (StringUtils.isEmpty(service)) {
  213. printError(resp, "service参数不能为空");
  214. throw new ServletException("service参数不能为空");
  215. }
  216. String serviceName = service.substring(0, service.lastIndexOf("."));
  217. String methodName = service.substring(service.lastIndexOf(".") + 1, service.length());
  218. String headerString = req.getParameter(ServiceRequest.POST_PARAM_HEADER);
  219. String paramString = req.getParameter(ServiceRequest.POST_PARAM_PARAMS);
  220. logger.debug("header:" + headerString);
  221. logger.debug("param:" + paramString);
  222. JSONObject headers = null;
  223. if (StringUtils.isNotEmpty(headerString)) {
  224. headers = JSON.parseObject(headerString);
  225. }
  226. JSONObject params = null;
  227. if (StringUtils.isNotEmpty(paramString)) {
  228. params = JSON.parseObject(paramString);
  229. }
  230. return new ServiceRequest(req, service, serviceName, methodName, headers, params, isMultiPart, fileMap);
  231. }
  232. private void initServiceInvoker() throws ServletException {
  233. WebApplicationContext applicationContext = WebApplicationContextUtils
  234. .getWebApplicationContext(getServletContext());
  235. if (applicationContext == null) {
  236. throw new ServletException("不能获取到Spring上下文");
  237. }
  238. this.serviceInvoker = applicationContext.getBean("serviceInvoker", ServiceInvoker.class);
  239. }
  240. }