/src/main/java/xjt/ws/core/ServiceInvokeServlet.java
Java | 255 lines | 183 code | 15 blank | 57 comment | 28 complexity | 3d3a753deb78fdcd04d1eddcc8d84dd6 MD5 | raw file
- package xjt.ws.core;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.PrintWriter;
- import java.net.URLEncoder;
- import java.util.HashMap;
- import java.util.Map;
- import javax.servlet.ServletConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.io.IOUtils;
- import org.apache.commons.lang.StringUtils;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.web.context.WebApplicationContext;
- import org.springframework.web.context.support.WebApplicationContextUtils;
- import org.springframework.web.multipart.MultipartException;
- import org.springframework.web.multipart.MultipartFile;
- import org.springframework.web.multipart.MultipartHttpServletRequest;
- import org.springframework.web.multipart.commons.CommonsMultipartResolver;
- import xjt.ws.invoker.ServiceInvoker;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- /**
- * Web服务调用的Servlet入口<br>
- * @author huzq
- * @author xjt
- */
- public class ServiceInvokeServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- private static final Logger logger = LoggerFactory.getLogger(ServiceInvokeServlet.class);
- private ServiceInvoker serviceInvoker;
- private String encoding = "utf-8";
- public void init(ServletConfig config) throws ServletException {
- super.init(config);
- initServiceInvoker();
- }
- /*
- *调用指定服务名的服务方法
- */
- protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding(encoding);
- logger.debug("请求编码:"+req.getCharacterEncoding());
- ServiceRequest serviceRequest = buildServiceRequest(req, resp);
- logger.debug("调用服务:" + serviceRequest);
- ServiceResponse serviceResponse = new ServiceResponse();
- try {
- this.serviceInvoker.invoke(serviceRequest,serviceResponse);
- }catch (Throwable t) {
- while(t.getCause()!=null){
- t = t.getCause();
- }
- logger.error("服务异常:", t);
- serviceResponse.setErrorInfo(t);
- }
- if(serviceResponse.isCached()){
- resp.reset();
- resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
- }else if (serviceResponse.isBinary()) {
- printBinary(resp, serviceResponse);
- } else {
- if (serviceResponse.isSuccess()) {
- printSuccess(resp, serviceResponse.getResults(),serviceResponse.getLastModifiedTime());
- } else {
- printError(resp, serviceResponse.getErrors(), serviceResponse.getErrorDetails());
- }
- }
- }
- /**
- * 输出二进制数据
- *
- * @param resp
- * @param serviceResp
- * @throws IOException
- */
- private void printBinary(HttpServletResponse resp, ServiceResponse serviceResp) throws IOException {
- resp.reset();
- ResponseFile file = serviceResp.getResponseFile();
- if (file == null) {
- printError(resp, "服务返回的文件流为空");
- return;
- }
- String fileName = file.getFileName();
- if (StringUtils.isNotEmpty(fileName)) {
- fileName = URLEncoder.encode(fileName,this.encoding);
- logger.debug("filename:"+fileName);
- resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
- resp.setHeader(ServiceResponse.RESPONSE_HEADER_FILE_NAME, fileName);
- }
- if (file.getLength() > 0) {
- resp.setContentLength((int)file.getLength());
- resp.setHeader(ServiceResponse.RESPONSE_HEADER_FILE_SIZE, file.getLength()+"");
- }
- if (serviceResp.getLastModifiedTime()!=null){
- resp.setHeader(ServiceResponse.RESPONSE_HEADER_LAST_MODIFIED_TIME, serviceResp.getLastModifiedTime());
- }else if (file.getLastModifiedTime() > 0) {
- resp.setHeader(ServiceResponse.RESPONSE_HEADER_LAST_MODIFIED_TIME, file.getLastModifiedTime() + "");
- }
-
- if(file.getPages()!=null){
- resp.setHeader(ServiceResponse.RESPONSE_HEADER_PAGES, file.getPages()+"");
- }
- resp.setContentType("application/octet-stream;charset="+encoding);
- if (file.getInputStream() != null) {
- ServletOutputStream os = null;
- InputStream is = null;
- try{
- is = file.getInputStream();
- os = resp.getOutputStream();
- IOUtils.copy(is, os);
- }finally{
- if(is!=null) {
- is.close();
- }
- if(os!=null){
- os.close();
- }
- }
- } else {
- printError(resp, "服务返回的文件流为空");
- }
- resp.flushBuffer();
- }
- /**
- * 输出成功的结果
- *
- * @param resp
- * @param results
- * @throws IOException
- */
- private void printSuccess(HttpServletResponse resp, Object results,String lastModifedTime) throws IOException {
- printText(resp, true, results, null, null,lastModifedTime);
- }
- /**
- * 输出错误信息
- *
- * @param resp
- * @param errors
- * @throws IOException
- */
- private void printError(HttpServletResponse resp, String errors) throws IOException {
- printText(resp, false, null, errors, null,null);
- }
- /**
- * 输出错误信息
- *
- * @param resp
- * @param errors
- * @param errorDetails
- * @throws IOException
- */
- private void printError(HttpServletResponse resp, String errors, String errorDetails) throws IOException {
- printText(resp, false, null, errors, errorDetails,null);
- }
- /**
- * 输出文本信息
- *
- * @param resp
- * @param results
- * @param success
- * @throws IOException
- */
- private void printText(HttpServletResponse resp, boolean success, Object results, String errors, String errorDetails,String lastModifiedTime)
- throws IOException {
- resp.reset();
- HashMap<Object,Object> resultMap = new HashMap<Object,Object>();
- if (success) {
- resp.setStatus(HttpServletResponse.SC_OK);
- if (results != null) {
- resultMap.put(ServiceResponse.RESULTS_PARAM_RESULTS, results);
- }
- } else {
- resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- resultMap.put(ServiceResponse.RESULTS_PARAM_ERRORS, errors);
- resultMap.put(ServiceResponse.RESULT_PARAM_ERROR_DETAILS, errorDetails);
- }
- resp.setContentType("application/json;charset="+encoding);
- if(lastModifiedTime!=null){
- resp.setHeader(ServiceResponse.RESPONSE_HEADER_LAST_MODIFIED_TIME, lastModifiedTime);
- }
- PrintWriter out = resp.getWriter();
- out.print(JSON.toJSONString(resultMap));
- resp.flushBuffer();
- out.close();
- }
- /**
- * 构造服务请求
- *
- * @param req
- * @param resp
- * @return
- * @throws MultipartException
- * @throws IOException
- * @throws ServletException
- */
- private ServiceRequest buildServiceRequest(HttpServletRequest req, HttpServletResponse resp)
- throws MultipartException, IOException, ServletException {
- CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(getServletContext());
- boolean isMultiPart = multipartResolver.isMultipart(req);
- logger.debug("multipart:" + isMultiPart);
- //MultipartFile[] files = null;
- Map<String,MultipartFile> fileMap = null;
- if (isMultiPart) {
- MultipartHttpServletRequest request = multipartResolver.resolveMultipart(req);
- fileMap = request.getFileMap();
- //files = (MultipartFile[]) fileMap.values().toArray(new MultipartFile[0]);
- req = request;
- }
- String service = StringUtils.trim(req.getParameter(ServiceRequest.POST_PARAM_SERVICE));
- if (StringUtils.isEmpty(service)) {
- printError(resp, "service参数不能为空");
- throw new ServletException("service参数不能为空");
- }
- String serviceName = service.substring(0, service.lastIndexOf("."));
- String methodName = service.substring(service.lastIndexOf(".") + 1, service.length());
- String headerString = req.getParameter(ServiceRequest.POST_PARAM_HEADER);
- String paramString = req.getParameter(ServiceRequest.POST_PARAM_PARAMS);
- logger.debug("header:" + headerString);
- logger.debug("param:" + paramString);
- JSONObject headers = null;
- if (StringUtils.isNotEmpty(headerString)) {
- headers = JSON.parseObject(headerString);
- }
- JSONObject params = null;
- if (StringUtils.isNotEmpty(paramString)) {
- params = JSON.parseObject(paramString);
- }
- return new ServiceRequest(req, service, serviceName, methodName, headers, params, isMultiPart, fileMap);
- }
- private void initServiceInvoker() throws ServletException {
- WebApplicationContext applicationContext = WebApplicationContextUtils
- .getWebApplicationContext(getServletContext());
- if (applicationContext == null) {
- throw new ServletException("不能获取到Spring上下文");
- }
- this.serviceInvoker = applicationContext.getBean("serviceInvoker", ServiceInvoker.class);
- }
- }