JobApiController.java 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package com.xxl.job.admin.controller;
  2. import com.xxl.job.admin.controller.annotation.PermessionLimit;
  3. import com.xxl.job.core.rpc.codec.RpcRequest;
  4. import com.xxl.job.core.rpc.codec.RpcResponse;
  5. import com.xxl.job.core.rpc.netcom.NetComServerFactory;
  6. import com.xxl.job.core.rpc.serialize.HessianSerializer;
  7. import com.xxl.job.core.util.HttpClientUtil;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14. import java.io.IOException;
  15. import java.io.OutputStream;
  16. /**
  17. * Created by xuxueli on 17/5/10.
  18. */
  19. @Controller
  20. public class JobApiController {
  21. private static Logger logger = LoggerFactory.getLogger(JobApiController.class);
  22. private RpcResponse doInvoke(HttpServletRequest request) {
  23. try {
  24. // deserialize request
  25. byte[] requestBytes = HttpClientUtil.readBytes(request);
  26. if (requestBytes == null || requestBytes.length==0) {
  27. RpcResponse rpcResponse = new RpcResponse();
  28. rpcResponse.setError("RpcRequest byte[] is null");
  29. return rpcResponse;
  30. }
  31. RpcRequest rpcRequest = (RpcRequest) HessianSerializer.deserialize(requestBytes, RpcRequest.class);
  32. // invoke
  33. RpcResponse rpcResponse = NetComServerFactory.invokeService(rpcRequest, null);
  34. return rpcResponse;
  35. } catch (Exception e) {
  36. logger.error(e.getMessage(), e);
  37. RpcResponse rpcResponse = new RpcResponse();
  38. rpcResponse.setError("Server-error:" + e.getMessage());
  39. return rpcResponse;
  40. }
  41. }
  42. @RequestMapping("/api")
  43. @PermessionLimit(limit=false)
  44. public void api(HttpServletRequest request, HttpServletResponse response) throws IOException {
  45. // invoke
  46. RpcResponse rpcResponse = doInvoke(request);
  47. // serialize response
  48. byte[] responseBytes = HessianSerializer.serialize(rpcResponse);
  49. response.setContentType("text/html;charset=utf-8");
  50. response.setStatus(HttpServletResponse.SC_OK);
  51. //baseRequest.setHandled(true);
  52. OutputStream out = response.getOutputStream();
  53. out.write(responseBytes);
  54. out.flush();
  55. }
  56. }