zoukankan      html  css  js  c++  java
  • (转)OpenFire源码学习之十七:HTTP Service插件

    转:http://blog.csdn.net/huwenfeng_2011/article/details/43457645

    HTTP Service插件

    这里的http接口插件是神马?

    Openfire主要是在消息推送,那么与其他系统的的消息怎么结合呢,那么这里这个HTTP Service插件就提供了一个基于HTTP的接口。为什么要提供这样的接口?在有些互联网的场景。一个用户平台可以是web的,当然也会有移动终端的APP,那么web端要给移动终端的APP发送消息就依赖这样的接口了。当然这里只是一种实现方式。

    首先查看在OF控制太的web页面

    本人这里做新增了短信接口。有业务场景的不同这里就不提出来了。

    接下来看看插件目录包:

    下面编写一个个业务类:

    JAVA部分

    HttpServiceServlet:

    [java] view plain copy
     
    1. @SuppressWarnings("deprecation")  
    2. public class HttpServiceServlet extends HttpServlet {  
    3.   
    4.     private static final long serialVersionUID = 1L;  
    5.     private HttpServicePlugin plugin;  
    6.     private RoutingTable routingTable;  
    7.     private SendMessageUtil sendMessageUtil;  
    8.     private SendMessageUtil messageUtil ;  
    9.     private static XmlPullParserFactory factory = null;  
    10.     private ThreadPool threadPool;  
    11.   
    12.       
    13.     static {  
    14.         try {  
    15.             factory = XmlPullParserFactory.newInstance(MXParser.class.getName(), null);  
    16.             factory.setNamespaceAware(true);  
    17.         }  
    18.         catch (XmlPullParserException e) {  
    19.             Log.error("Error creating a parser factory", e);  
    20.         }  
    21.     }  
    22.       
    23.     @Override  
    24.     public void init(ServletConfig servletConfig) throws ServletException {  
    25.         super.init(servletConfig);  
    26.         plugin = (HttpServicePlugin) XMPPServer.getInstance().getPluginManager().getPlugin("httpedu");  
    27.         AuthCheckFilter.addExclude("httpedu/httpservice");  
    28.           
    29.         if (null == routingTable)  
    30.             routingTable = XMPPServer.getInstance().getRoutingTable();  
    31.         if (null == sendMessageUtil)  
    32.             sendMessageUtil = new SendMessageUtil();  
    33.         if (null == threadPool)  
    34.             threadPool = new ThreadPool(10);   
    35.           
    36.     }  
    37.   
    38.     @SuppressWarnings("unused")  
    39.     @Override  
    40.     protected void doGet(HttpServletRequest request, HttpServletResponse response)  
    41.             throws ServletException, IOException  
    42.     {  
    43.           
    44.         PrintWriter out = response.getWriter();  
    45.         
    46.         BufferedReader reader = request.getReader();  
    47.         StringBuffer buffer = new StringBuffer();  
    48.         String string="";  
    49.         while ((string = reader.readLine()) != null) {  
    50.             String x = new String(string.getBytes("ISO-8859-1"), "UTF-8");   
    51.             buffer.append(x);  
    52.         }  
    53.         reader.close();  
    54.           
    55.   
    56.         // Check that our plugin is enabled.  
    57.         if (!plugin.isEnabled()) {  
    58.             Log.warn("http service plugin is disabled: " + request.getQueryString());  
    59.             replyError("Error1002",response, out);  
    60.             return;  
    61.         }  
    62.          
    63.         // Check the request type and process accordingly  
    64.         try {  
    65.             JSONObject object = new org.json.JSONObject(buffer.toString());  
    66.             if(null == object){  
    67.                 Log.warn("json is null " + request.getQueryString());  
    68.                 replyError("Error1003",response, out);  
    69.                 return;  
    70.             }  
    71.             //参数  
    72.             String secret = object.getString("secret").trim();  
    73.             String optType = object.getString("optType").trim();  
    74.             String fromid = object.getString("sender").trim();  
    75.             String domain = object.getString("domain").trim();  
    76.             String resources = object.getString("resources").trim();  
    77.             ......  
    78.               
    79.             String schoolid = object.getString("schoolid").trim();  
    80.                 
    81.               
    82.             // Check this request is authorised  
    83.             if (secret == null || !secret.equals(plugin.getSecret())){  
    84.                 Log.warn("secret is error: " + request.getQueryString());  
    85.                 replyError("Error1004",response, out);  
    86.                 return;  
    87.             }  
    88.             ......  
    89.               
    90.             if (null == messageUtil)  
    91.                 messageUtil = new SendMessageUtil();   
    92.               
    93.             if ("1".equals(optType)){  
    94.                 //Personal business to send separately  
    95.                 if(toIds == null || "".equals(toIds)){  
    96.                     Log.warn("toIds is error: " + request.getQueryString());  
    97.                     replyError("Error1020",response, out);  
    98.                     return;  
    99.                 }  
    100.                 try {  
    101.                     threadPool.execute(createTask(object,routingTable));  
    102.                       
    103.                     replyMessage("ok", response, out);  
    104.                       
    105.                 } catch (Exception e) {  
    106.                       
    107.                     Log.warn("toIds is error: " + request.getQueryString());  
    108.                 }  
    109.                   
    110.                   
    111.             }  
    112.             else {  
    113.                 Log.warn("opttype is error: " + request.getQueryString());  
    114.                 replyError("Error1021",response, out);  
    115.             }  
    116.         }  
    117.         catch (IllegalArgumentException e) {  
    118.             Log.error("IllegalArgumentException: ", e);  
    119.             replyError("Ex1002",response, out);  
    120.         }  
    121.         catch (Exception e) {  
    122.             Log.error("Exception: ", e);  
    123.             replyError("Ex1001",response, out);  
    124.         }  
    125.     }  
    126.   
    127.     @SuppressWarnings("unused")  
    128.     private void replyMessage(String message,HttpServletResponse response, PrintWriter out){  
    129.         response.setContentType("text/xml");          
    130.         out.println("<result>" + message + "</result>");  
    131.         out.flush();  
    132.     }  
    133.   
    134.     private void replyError(String error,HttpServletResponse response, PrintWriter out){  
    135.         response.setContentType("text/xml");          
    136.         out.println("<error>" + error + "</error>");  
    137.         out.flush();  
    138.     }  
    139.       
    140.     @Override  
    141.     protected void doPost(HttpServletRequest request, HttpServletResponse response)  
    142.             throws ServletException, IOException {  
    143.         doGet(request, response);  
    144.     }  
    145.   
    146.     @Override  
    147.     public void destroy() {  
    148.         threadPool.waitFinish();  
    149.         threadPool.closePool();  
    150.         super.destroy();  
    151.         // Release the excluded URL  
    152.         AuthCheckFilter.removeExclude("httpedu/httpservice");  
    153.     }  
    154.   
    155.     private static Runnable createTask(final JSONObject object,final RoutingTable routingTable) {     
    156.         return new Runnable() {     
    157.             public void run() {  
    158.                 SendMessageUtil messageUtil = new SendMessageUtil();  
    159.                 try {  
    160.                     messageUtil.sendSingleMessage(object,routingTable);  
    161.                 } catch (JSONException e) {  
    162.                     e.printStackTrace();  
    163.                 }  
    164.             }     
    165.        };     
    166.    }   
    167. }  

    HttpServicePlugin:

    [java] view plain copy
     
    1. /** 
    2.  * Plugin that allows the administration of https via HTTP requests. 
    3.  * 
    4.  * @author huwf 
    5.  */  
    6. public class HttpServicePlugin implements Plugin, PropertyEventListener {  
    7.     private XMPPServer server;  
    8.   
    9.     private String secret;  
    10.     private boolean enabled;  
    11.     private String smsAddrs;  
    12.     private SendThread sendThread;  
    13.   
    14.     public void initializePlugin(PluginManager manager, File pluginDirectory) {  
    15.         server = XMPPServer.getInstance();  
    16.   
    17.         secret = JiveGlobals.getProperty("plugin.httpservice.secret", "");  
    18.         // If no secret key has been assigned to the http service yet, assign a random one.  
    19.         if (secret.equals("")){  
    20.             secret = StringUtils.randomString(8);  
    21.             setSecret(secret);  
    22.         }  
    23.           
    24.         // See if the service is enabled or not.  
    25.         enabled = JiveGlobals.getBooleanProperty("plugin.httpservice.enabled", false);  
    26.   
    27.         // Get the list of IP addresses that can use this service. An empty list means that this filter is disabled.  
    28.         smsAddrs = JiveGlobals.getProperty("plugin.httpservice.smsAddrs", "");  
    29.   
    30.         // Listen to system property events   
    31.         PropertyEventDispatcher.addListener(this);  
    32.           
    33.         if (null == sendThread)  
    34.             sendThread = new SendThread();  
    35.     }  
    36.   
    37.     public void destroyPlugin() {  
    38.         // Stop listening to system property events  
    39.         PropertyEventDispatcher.removeListener(this);  
    40.     }  
    41.       
    42.     /** 
    43.      * Returns the secret key that only valid requests should know. 
    44.      * 
    45.      * @return the secret key. 
    46.      */  
    47.     public String getSecret() {  
    48.         return secret;  
    49.     }  
    50.   
    51.     /** 
    52.      * Sets the secret key that grants permission to use the httpservice. 
    53.      * 
    54.      * @param secret the secret key. 
    55.      */  
    56.     public void setSecret(String secret) {  
    57.         JiveGlobals.setProperty("plugin.httpservice.secret", secret);  
    58.         this.secret = secret;  
    59.     }  
    60.   
    61.   
    62.     public String getSmsAddrs() {  
    63.         return smsAddrs;  
    64.     }  
    65.   
    66.     public void setSmsAddrs(String smsAddrs) {  
    67.         JiveGlobals.setProperty("plugin.httpservice.smsAddrs", smsAddrs);  
    68.         this.smsAddrs = smsAddrs;  
    69.     }  
    70.   
    71.     /** 
    72.      * Returns true if the http service is enabled. If not enabled, it will not accept 
    73.      * requests to create new accounts. 
    74.      * 
    75.      * @return true if the http service is enabled. 
    76.      */  
    77.     public boolean isEnabled() {  
    78.         return enabled;  
    79.     }  
    80.   
    81.     /** 
    82.      * Enables or disables the http service. If not enabled, it will not accept 
    83.      * requests to create new accounts. 
    84.      * 
    85.      * @param enabled true if the http service should be enabled. 
    86.      */  
    87.     public void setEnabled(boolean enabled) {  
    88.         this.enabled = enabled;  
    89.         JiveGlobals.setProperty("plugin.httpservice.enabled",  enabled ? "true" : "false");  
    90.     }  
    91.   
    92.     public void propertySet(String property, Map<String, Object> params) {  
    93.         if (property.equals("plugin.httpservice.secret")) {  
    94.             this.secret = (String)params.get("value");  
    95.         }  
    96.         else if (property.equals("plugin.httpservice.enabled")) {  
    97.             this.enabled = Boolean.parseBoolean((String)params.get("value"));  
    98.         }  
    99.         else if (property.equals("plugin.httpservice.smsAddrs")) {  
    100.             this.smsAddrs = (String)params.get("smsAddrs");  
    101.         }  
    102.     }  
    103.   
    104.     public void propertyDeleted(String property, Map<String, Object> params) {  
    105.         if (property.equals("plugin.httpservice.secret")) {  
    106.             this.secret = "";  
    107.         }  
    108.         else if (property.equals("plugin.httpservice.enabled")) {  
    109.             this.enabled = false;  
    110.         }  
    111.         else if (property.equals("plugin.httpservice.smsAddrs")) {  
    112.             this.smsAddrs = "";  
    113.         }  
    114.     }  
    115.   
    116.     public void xmlPropertySet(String property, Map<String, Object> params) {  
    117.         // Do nothing  
    118.     }  
    119.   
    120.     public void xmlPropertyDeleted(String property, Map<String, Object> params) {  
    121.         // Do nothing  
    122.     }  
    123.   
    124. }  

    SendThread:

    [java] view plain copy
     
    1. public class SendThread {  
    2.     ......  
    3.       
    4.     static{  
    5.         ssu = new SendSmsUtil();  
    6.         httpServicePlugin = (HttpServicePlugin) XMPPServer.getInstance().getPluginManager().getPlugin("httpedu");  
    7.         client = new HttpClient();  
    8.         initialize(client);  
    9.         executor = new ThreadPoolExecutor(1, 3, 3*1000, TimeUnit.MILLISECONDS, executeQueue, new RejectedHandler());  
    10.     }  
    11.       
    12.     private static void initialize(HttpClient client){  
    13.         MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();  
    14.         HttpConnectionManagerParams connectionParams = connectionManager.getParams();  
    15.         connectionParams.setConnectionTimeout(2000);  
    16.         connectionParams.setDefaultMaxConnectionsPerHost(500);  
    17.         connectionParams.setMaxTotalConnections(500);  
    18.         client.setHttpConnectionManager(connectionManager);  
    19.           
    20.         HttpClientParams httpParams = client.getParams();  
    21.         httpParams.setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() {  
    22.             @Override  
    23.             public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) {  
    24.                 if(method == null){  
    25.                     return false;  
    26.                 }  
    27.                 if(executionCount > MAX_RETRY_COUNT){  
    28.                     return false;  
    29.                 }  
    30.                 if(!method.isRequestSent()){  
    31.                     return true;  
    32.                 }  
    33.                 if(exception instanceof NoHttpResponseException){  
    34.                     return true;  
    35.                 }  
    36.                 return false;  
    37.             }  
    38.         });  
    39.     }  
    40.       
    41.     public static boolean push(SmsEnity msg){  
    42.         return push(msg, false);  
    43.     }  
    44.       
    45.     public static boolean push(final SmsEnity msg, boolean reliable){  
    46.         PostMethod postMethod = null;  
    47.         try {  
    48.             String urlAddrs = httpServicePlugin.getSmsAddrs();  
    49.             postMethod = createPostMethod(msg, urlAddrs);  
    50.             client.executeMethod(postMethod);  
    51.               
    52.             int statusCode = postMethod.getStatusCode();  
    53.             if(statusCode == HttpStatus.SC_OK){  
    54.                 String retMsg = new String(postMethod.getResponseBody());  
    55.                 retMsg = URLDecoder.decode(retMsg, "UTF-8");  
    56.                   
    57.                 if("".equals(retMsg) || null == retMsg){  
    58.                     LOG.info("sms send success! sendid: " + msg.getSendid() + " Receiveid: " + msg.getReceiveid() + " Content: " + msg.getContent());  
    59.                 }else{  
    60.                     throw new PushException(retMsg);  
    61.                 }  
    62.   
    63.                 return true;  
    64.                   
    65.             }else if(statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR){  
    66.                 throw new PushException("Push server internal error: " + HttpStatus.SC_INTERNAL_SERVER_ERROR);  
    67.             }  
    68.         }catch (IOException e1) {  
    69.             if(reliable){  
    70.                 try {  
    71.                     failQueue.put(new Runnable() {  
    72.                         public void run() {  
    73.                             push(msg,true);  
    74.                         }  
    75.                     });  
    76.                     LOG.info(Thread.currentThread().getName()+": in the queue...");  
    77.                     if(!start){  
    78.                         startup();  
    79.                     }  
    80.                 } catch (InterruptedException e) {  
    81.                     e.printStackTrace();  
    82.                 }  
    83.             }  
    84.         }catch(PushException e2){  
    85.             LOG.info("The sms Push failure and throws PushException" + e2.getMessage() + " "   
    86.                     + "sms content-> Sendid:" +  msg.getSendid() + " Receiveid: " + msg.getReceiveid() +  
    87.                     " Content: " + msg.getContent() + " Sendtype:" + msg.getSendtype());  
    88.         }catch(Exception e3){  
    89.             LOG.info("The sms Push failure and throws PushException" + e3.getMessage() + " "   
    90.                     + "sms content-> Sendid:" +  msg.getSendid() + " Receiveid: " + msg.getReceiveid() +  
    91.                     " Content: " + msg.getContent() + " Sendtype:" + msg.getSendtype());  
    92.         }finally{  
    93.             postMethod.releaseConnection();  
    94.         }  
    95.           
    96.         return false;  
    97.     }  
    98.       
    99.     private static PostMethod createPostMethod(SmsEnity se, String uri) throws Exception{  
    100.         PostMethod postMethod = null;  
    101.         postMethod = new PostMethod(uri);  
    102.           
    103.         if (null != se.getSendid() && !"".equals(se.getSendid()))  
    104.             postMethod.addParameter(new NameValuePair("sendid", se.getSendid()));  
    105.           
    106.         if (null != se.getToken() && !"".equals(se.getSendid()))  
    107.             postMethod.addParameter(new NameValuePair("token", se.getToken()));  
    108.           
    109.         postMethod.addParameter(new NameValuePair("sendtype", se.getSendtype() != null ? se.getSendtype() : ""));  
    110.           
    111.         if (null != se.getReceiveid() && !"".equals(se.getReceiveid()))  
    112.             postMethod.addParameter(new NameValuePair("receiveid", se.getReceiveid()));  
    113.           
    114.         if (null != se.getClassid() && !"".equals(se.getClassid()))  
    115.             postMethod.addParameter(new NameValuePair("classid", se.getClassid()));  
    116.           
    117.         postMethod.addParameter(new NameValuePair("schoolid", se.getSchoolid() != null ? se.getSchoolid() : ""));  
    118.           
    119.         if (null != se.getGroupid() && !"".equals(se.getGroupid()))  
    120.             postMethod.addParameter(new NameValuePair("groupid", se.getGroupid()));  
    121.           
    122.         if (null != se.getSerial_num() && !"".equals(se.getSerial_num()))  
    123.             postMethod.addParameter(new NameValuePair("serial_num", se.getSerial_num()));  
    124.           
    125.         if (null != se.getContent() && !"".equals(se.getContent()))  
    126.             postMethod.addParameter(new NameValuePair("content", se.getContent()));  
    127.           
    128.           
    129.         return postMethod;  
    130.     }  
    131.       
    132.     /** 
    133.      * Start a background thread 
    134.      */  
    135.     private synchronized static void startup(){  
    136.         LOG.info(Thread.currentThread().getName()+" : Start a background thread...");  
    137.         if(!start){  
    138.             start = true;  
    139.             worker = new Thread(){  
    140.                 @Override  
    141.                 public void run() {  
    142.                     workStart(this);  
    143.                 }  
    144.             };  
    145.             worker.setName("worker thread");  
    146.             worker.start();  
    147.         }  
    148.     }  
    149.       
    150.     /** 
    151.      * Submit to perform tasks 
    152.      * @param thread 
    153.      */  
    154.     private static void workStart(Thread thread){  
    155.         while(start && worker == thread){  
    156.             Runnable task = failQueue.poll();  
    157.             LOG.info(Thread.currentThread().getName()+" : The queue of the communist party of China has a number of tasks: " + failQueue.size());  
    158.             LOG.info(Thread.currentThread().getName()+" : From the queue"+task==null?"no":""+"Take out the task...");  
    159.             if(task != null){  
    160.                 executor.execute(task);  
    161.             }else{  
    162.                 try {  
    163.                     Thread.sleep(5*1000);  
    164.                 } catch (InterruptedException e) {  
    165.                     e.printStackTrace();  
    166.                 }  
    167.             }  
    168.         }  
    169.     }  
    170.       
    171.     /** 
    172.      * Denial of service processing strategy 
    173.      */  
    174.     static class RejectedHandler implements RejectedExecutionHandler{  
    175.         public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {  
    176.             if(!executor.isShutdown()){  
    177.                 if(!executor.isTerminating()){  
    178.                     try {  
    179.                         failQueue.put(task);  
    180.                     } catch (InterruptedException e) {  
    181.                         e.printStackTrace();  
    182.                     }  
    183.                 }  
    184.             }  
    185.         }  
    186.     }  
    187. }  

    ThreadPool:

    [java] view plain copy
     
    1. @SuppressWarnings("rawtypes")  
    2. public class ThreadPool extends ThreadGroup {  
    3.   
    4.     // thread pool closed  
    5.     private boolean isClosed = false;  
    6.     private LinkedList workQueue;  
    7.     private static int threadPoolID = 1;  
    8.   
    9.     /** 
    10.      * created and started for work thread 
    11.      *  
    12.      * @param poolSize 
    13.      *            the thread size in pool 
    14.      */  
    15.     public ThreadPool(int poolSize) {  
    16.         super(threadPoolID + "");  
    17.         setDaemon(true);  
    18.         workQueue = new LinkedList();  
    19.         for (int i = 0; i < poolSize; i++) {  
    20.             new WorkThread(i).start();  
    21.         }  
    22.     }  
    23.   
    24.     /** 
    25.      * Work queue to add a new task, the worker thread to execute the office 
    26.      *  
    27.      * @param task 
    28.      */  
    29.     @SuppressWarnings("unchecked")  
    30.     public synchronized void execute(Runnable task) {  
    31.         if (isClosed) {  
    32.             throw new IllegalStateException();  
    33.         }  
    34.         if (task != null) {  
    35.             // Adding a task to the queue  
    36.             workQueue.add(task);  
    37.             // Wake one being getTask () method to be the work of the task  
    38.             // threads  
    39.             notify();  
    40.         }  
    41.     }  
    42.   
    43.     /** 
    44.      * Removed from the work queue a task, the worker thread will call this 
    45.      * method 
    46.      *  
    47.      * @param threadid 
    48.      * @return 
    49.      * @throws InterruptedException 
    50.      */  
    51.     private synchronized Runnable getTask(int threadid)  
    52.             throws InterruptedException {  
    53.         while (workQueue.size() == 0) {  
    54.             if (isClosed)  
    55.                 return null;  
    56.             System.out.println("work thread:" + threadid + "wait task...");  
    57.             // If no work queue task waits for the task  
    58.             wait();  
    59.         }  
    60.         System.out.println("work thread:" + threadid + "start run task");  
    61.         // Inverse return the first element in the queue, and removed from the  
    62.         // queue  
    63.         return (Runnable) workQueue.removeFirst();  
    64.     }  
    65.   
    66.     /** 
    67.      * close thread pool 
    68.      */  
    69.     public synchronized void closePool() {  
    70.         if (!isClosed) {  
    71.             // After waiting worker threads  
    72.             waitFinish();  
    73.             isClosed = true;  
    74.             // Empty the work queue and interrupt the thread pool thread for all  
    75.             // the work,  
    76.             // this method inherited from class ThreadGroup  
    77.             workQueue.clear();  
    78.             interrupt();  
    79.         }  
    80.     }  
    81.   
    82.     /** 
    83.      * Waiting for a worker to perform all tasks completed 
    84.      */  
    85.     public void waitFinish() {  
    86.         synchronized (this) {  
    87.             isClosed = true;  
    88.             // Wake up all still getTask () method to wait for the task worker  
    89.             // thread  
    90.             notifyAll();  
    91.         }  
    92.         // Return of active threads in this thread group estimates.  
    93.         Thread[] threads = new Thread[activeCount()];  
    94.         // enumerate () method inherited from ThreadGroup class,  
    95.         // according to the estimated value of active threads in the thread  
    96.         // group to get  
    97.         // all currently active worker threads  
    98.         int count = enumerate(threads);  
    99.         for (int i = 0; i < count; i++) {  
    100.             try {  
    101.                 threads[i].join();  
    102.             } catch (InterruptedException ex) {  
    103.                 ex.printStackTrace();  
    104.             }  
    105.         }  
    106.     }  
    107.   
    108.     /** 
    109.      * Inner classes, the worker thread is responsible for removing the task 
    110.      * from the work queue and executes 
    111.      *  
    112.      * @author huwf 
    113.      *  
    114.      */  
    115.     private class WorkThread extends Thread {  
    116.         private int id;  
    117.   
    118.         public WorkThread(int id) {  
    119.             // Parent class constructor, the thread is added to the current  
    120.             // ThreadPool thread group  
    121.             super(ThreadPool.this, id + "");  
    122.             this.id = id;  
    123.         }  
    124.   
    125.         public void run() {  
    126.             // isInterrupted () method inherited from the Thread class,  
    127.             // to determine whether the thread is interrupted  
    128.             while (!isInterrupted()) {  
    129.                 Runnable task = null;  
    130.                 try {  
    131.                     task = getTask(id);  
    132.                 } catch (InterruptedException ex) {  
    133.                     ex.printStackTrace();  
    134.                 }  
    135.                 // If getTask () returns null or thread getTask () is  
    136.                 // interrupted, then the end of this thread  
    137.                 if (task == null)  
    138.                     return;  
    139.   
    140.                 try {  
    141.                     // run task;  
    142.                     task.run();  
    143.                 } catch (Throwable t) {  
    144.                     t.printStackTrace();  
    145.                 }  
    146.             }  
    147.         }  
    148.     }  
    149.   
    150. }  

    SendMessageUtil:

    [java] view plain copy
     
    1. public class SendMessageUtil {  
    2.   
    3.     private static Map<Integer, XMPPPacketReader> parsers = new ConcurrentHashMap<Integer, XMPPPacketReader>();  
    4.     private static XmlPullParserFactory factory = null;  
    5.   
    6.     private static final Logger log = LoggerFactory  
    7.             .getLogger(SendMessageUtil.class);  
    8.   
    9.     /** 
    10.      * Send a single message interface 
    11.      * @throws JSONException  
    12.      */  
    13.     public String sendSingleMessage(JSONObject ae,RoutingTable routingTable) throws JSONException {  
    14.         String state = "failure";  
    15.           
    16.         SmsEnity se = new SmsEnity();  
    17.         String fromid = ae.getString("sender");  
    18.         String domain = ae.getString("domain");  
    19.         String resources = ae.getString("resources");  
    20.         String toId = ae.getString("toIds");  
    21.         String msgType = ae.getString("msgType");  
    22.         String msgNo = ae.getString("msgNo");  
    23.         String smsType = ae.getString("smsType");  
    24.         //RoutingTable routingTable = ae.getRoutingTable();  
    25.         String token = "";//暂时为空  
    26.         String smsBody = ae.getString("smsBody");  
    27.         String schoolid = ae.getString("schoolid");  
    28.           
    29.         //0指定用户发送,1给学生发送,2全班发送,3,多个班级发送 6.发给学生家长你那发给老师是0  
    30.         String rectype = ae.getString("rectype");  
    31.           
    32.         String classid = "";  
    33.         if ("10014".equals(msgType)){  
    34.             classid = ae.getString("classId");  
    35.         }  
    36.         String sender = fromid + "@" + domain + "/" + resources;  
    37.         StringBuffer sb = new StringBuffer();  
    38.         if (toId.length() > 0) {  
    39.             String tos[] = toId.split(",");  
    40.             for (int i = 0; i < tos.length; i++) {  
    41.                 String to = tos[i] + "@" + domain;  
    42.                 Message packet;  
    43.                 if (!sender.contains(to) && !sender.equals(to)) {  
    44.                     packet = assemblyMessages(to, sender, "1", msgType, msgNo,  
    45.                             null, null, null,classid);  
    46.                     if ("2".equals(smsType))  
    47.                         sb.append(tos[i] + ",");  
    48.                     PacketRouter router = XMPPServer.getInstance().getPacketRouter();  
    49.                     router.route(packet);  
    50.                     log.info("send: " + packet);  
    51.                     state = "ok";  
    52.                     if ("1".equals(smsType)){  
    53.                         if (null == routingTable.getClientRoute(new JID(to + "/" + resources)))   
    54.                             sb.append(tos[i] + ",");  
    55.                           
    56.                     }  
    57.                 }  
    58.                   
    59.             }  
    60.             String receiveids = sb.toString();  
    61.             // Send SMS  
    62.             if (!"".equals(smsType) && receiveids.length() > 0 && null != rectype) {  
    63.                 se.setSendid(fromid);  
    64.                 se.setToken(token);  
    65.                 if (",".equals(sb.substring(sb.length() - 1)))  
    66.                     receiveids = receiveids.substring(0,receiveids.length() - 1);  
    67.                   
    68.                 se.setSendtype(rectype);  
    69.                 se.setReceiveid(receiveids);  
    70.                 String body;  
    71.                 try {  
    72.                     body = java.net.URLEncoder.encode(smsBody, "UTF-8");  
    73.                     se.setContent(body);  
    74.                 } catch (UnsupportedEncodingException e) {  
    75.                     log.error("send sms UnsupportedEncodingException:"+e.getMessage());  
    76.                 }  
    77.                 se.setSchoolid(schoolid);  
    78.                 se.setGroupid("");  
    79.                 se.setClassid("");  
    80.                 se.setSerial_num(String.valueOf(System.currentTimeMillis()));  
    81.                 SendThread.push(se);  
    82.             }  
    83.         }  
    84.         return state;  
    85.     }  
    86.       
    87.     public  boolean isDigit(String sender, String to){  
    88.         return to.contains(sender) ;  
    89.     }  
    90.   
    91.     /** 
    92.      * Send group business messages 
    93.      */  
    94.     public String sendGroupMessage(AdditionalEntities ae) {  
    95.         //短信发送  
    96.     }  
    97.   
    98.     /** 
    99.      * The message format assembled 
    100.      */  
    101.     public Message assemblyMessages(String to...) {  
    102.         //封装消息  
    103.         return packet;  
    104.     }  
    105. }  

    Web部分

    web-custom.xml

    [html] view plain copy
     
    1. <?xml version='1.0' encoding='ISO-8859-1'?>  
    2. <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">  
    3. <web-app>  
    4.     <!-- Servlets -->  
    5.     <servlet>  
    6.         <servlet-name>HttpServiceServlet</servlet-name>  
    7.         <servlet-class>com.....httpedu.httpservlet.HttpServiceServlet</servlet-class>  
    8.     </servlet>  
    9.   
    10.     <!-- Servlet mappings -->  
    11.     <servlet-mapping>   
    12.         <servlet-name>HttpServiceServlet</servlet-name>  
    13.         <url-pattern>/httpservice</url-pattern>  
    14.     </servlet-mapping>  
    15.   
    16. </web-app>  

    http-service.jsp

    [html] view plain copy
     
    1. <%@ page import="java.util.*,  
    2.                  org.jivesoftware.openfire.XMPPServer,  
    3.                  org.jivesoftware.util.*,  
    4.                  com.montnets.httpedu.plugin.HttpServicePlugin"  
    5.     errorPage="error.jsp"  
    6. %>  
    7.   
    8. <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>  
    9. <%@ taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt" %>  
    10.   
    11. <%-- Define Administration Bean --%>  
    12. <jsp:useBean id="admin" class="org.jivesoftware.util.WebManager"  />  
    13. <c:set var="admin" value="${admin.manager}" />  
    14. <% admin.init(request, response, session, application, out ); %>  
    15.   
    16. <%  // Get parameters  
    17.     boolean save = request.getParameter("save") != null;  
    18.     boolean success = request.getParameter("success") != null;  
    19.     String secret = ParamUtils.getParameter(request, "secret");  
    20.     boolean enabled = ParamUtils.getBooleanParameter(request, "enabled");  
    21.     String smsAddrs = ParamUtils.getParameter(request, "smsAddrs");  
    22.     //注意:这里getPlugin("httpedu")里面的参数是插件的目录名称  
    23.     HttpServicePlugin plugin = (HttpServicePlugin) XMPPServer.getInstance().getPluginManager().getPlugin("httpedu");  
    24.   
    25.     // Handle a save  
    26.     Map errors = new HashMap();  
    27.     if (save) {  
    28.         if (errors.size() == 0) {  
    29.             plugin.setEnabled(enabled);  
    30.             plugin.setSecret(secret);  
    31.             plugin.setSmsAddrs(smsAddrs);  
    32.             response.sendRedirect("http-service.jsp?success=true");  
    33.             return;  
    34.         }  
    35.     }  
    36.   
    37.     secret = plugin.getSecret();  
    38.     enabled = plugin.isEnabled();  
    39.     smsAddrs = plugin.getSmsAddrs();  
    40.       
    41. %>  
    42.   
    43. <html>  
    44.     <head>  
    45.         <title>HTTP Service Properties</title>  
    46.         <meta name="pageID" content="http-service"/>  
    47.     </head>  
    48.     <body>  
    49.   
    50.   
    51. <p>  
    52. This is an HTTP service plug-in     
    53. it is mainly to complete business push message center system and off-line message interface implementation  
    54. </p>  
    55.   
    56. <%  if (success) { %>  
    57.   
    58.     <div class="jive-success">  
    59.     <table cellpadding="0" cellspacing="0" border="0">  
    60.     <tbody>  
    61.         <tr><td class="jive-icon"><img src="images/success-16x16.gif" width="16" height="16" border="0"></td>  
    62.         <td class="jive-icon-label">  
    63.             HTTP service properties edited successfully.  
    64.         </td></tr>  
    65.     </tbody>  
    66.     </table>  
    67.     </div><br>  
    68. <% } %>  
    69.   
    70. <form action="http-service.jsp?save" method="post">  
    71.   
    72. <fieldset>  
    73.     <legend>HTTP Service</legend>  
    74.     <div>  
    75.     <p>  
    76.     This main set message center call switch, text messaging and SMS address configuration  
    77.     </p>  
    78.     <ul>  
    79.         <input type="radio" name="enabled" value="true" id="hrb01"  
    80.         <%= ((enabled) ? "checked" : "") %>>  
    81.         <label for="hrb01"><b>Enabled</b> - HTTP service requests will be processed.</label>  
    82.         <br>  
    83.         <input type="radio" name="enabled" value="false" id="hrb02"  
    84.          <%= ((!enabled) ? "checked" : "") %>>  
    85.         <label for="hrb02"><b>Disabled</b> - HTTP service requests will be ignored.</label>  
    86.         <br><br>  
    87.   
    88.         <label for="h_text_secret">Secret key:</label>  
    89.         <input type="text" name="secret" value="<%= secret %>" id="h_text_secret">  
    90.         <br><br>  
    91.   
    92.         <label for="h_smsAddrs">SMS address:</label>  
    93.         <input type="text" id="h_smsAddrs" name="smsAddrs" size="80" value="<%= smsAddrs == null ? "" : smsAddrs %>"/>  
    94.     </ul>  
    95.     </div>  
    96. </fieldset>  
    97.   
    98. <br><br>  
    99.   
    100. <input type="submit" value="Save Settings">  
    101.   
    102. </form>  
    103. </body>  
    104. </html>  

    Plugin.xml:

    [html] view plain copy
     
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2.   
    3. <plugin>  
    4.     <class>com.montnets.httpedu.plugin.HttpServicePlugin</class>  
    5.     <name>Http Service</name>  
    6.     <description>The message center services and A short letter to push</description>  
    7.     <author>HuWenFeng</author>  
    8.     <version>1.4.2</version>  
    9.     <date>10/7/2013</date>  
    10.     <minServerVersion>3.5.1</minServerVersion>  
    11.       
    12.     <adminconsole>          
    13.         <tab id="tab-server">  
    14.             <sidebar id="sidebar-server-settings">  
    15.                 <item id="http-service" name="Http Service" url="http-service.jsp"  
    16.                      description="The message center services and A short letter to push" />  
    17.             </sidebar>  
    18.         </tab>  
    19.     </adminconsole>  
    20.   
    21. </plugin>  

    测试

    TestHttpedu:

    [java] view plain copy
     
    1. public class TestHttpedu {  
    2.   
    3.     public static void main(String[] args) throws JSONException, InterruptedException {  
    4.         String datetime = (new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS")).format(new Date());  
    5.         System.out.println(datetime);  
    6.         int a = 0;  
    7.         for (int i=0;i<1;i++){  
    8.             MyThread my = new MyThread(a++);  
    9.             my.start();  
    10.             my.sleep(100);  
    11.         }  
    12.     }  
    13. }  

    MyThread:

    [java] view plain copy
     
    1. public class MyThread extends Thread{  
    2.   
    3.     private int i;  
    4.   
    5.     public MyThread(int i){  
    6.         this.i=i;  
    7.     }  
    8.     public void run(){  
    9.         httpedu();  
    10.     }  
    11.       
    12.     public void httpedu(){  
    13.         JSONObject jb = new JSONObject();  
    14.         try {  
    15.             jb.put("secret", "montnets@123");//montnets@123  
    16.             jb.put("optType", "1");  
    17.             //你需要发送的参数  
    18.             try {  
    19.                 testPost(jb);  
    20.             } catch (IOException e) {  
    21.                 e.printStackTrace();  
    22.             }  
    23.         } catch (JSONException e) {  
    24.             e.printStackTrace();  
    25.         }  
    26.     }  
    27.       
    28.     public void testPost(JSONObject json) throws IOException, JSONException {   
    29.         URL url = new URL("http://127.0.0.1:9090/plugins/httpedu/httpservice");    
    30.         URLConnection connection = url.openConnection();  
    31.         connection.setDoOutput(true);  
    32.         OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");  
    33.           
    34.         String j = json.toString();  
    35.         out.write(j);  
    36.         out.flush();    
    37.         out.close();  
    38.         //返回  
    39.         String sCurrentLine;    
    40.         String sTotalString;    
    41.         sCurrentLine = "";    
    42.         sTotalString = "";   
    43.         InputStream l_urlStream;    
    44.         l_urlStream = connection.getInputStream();    
    45.         BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream));    
    46.         while ((sCurrentLine = l_reader.readLine()) != null) {    
    47.             sTotalString += sCurrentLine;    
    48.         }    
    49.           
    50.         System.out.println("返回第 " +i + " 结果:" + sTotalString);    
    51.         if(sTotalString.indexOf("ok")==-1){  
    52.             System.out.println(sTotalString+" : " + json.toString());  
    53.         }  
    54.     }  
  • 相关阅读:
    Android ANR异常解决方案
    数据结构之斐波那契查找
    数据结构之插值查找
    数据结构之折半查找
    Android Task 任务
    java中“==”号的运用
    php中向前台js中传送一个二维数组
    array_unique和array_flip 实现去重间的区别
    js new Date() 获取时间
    手机端html5触屏事件(touch事件)
  • 原文地址:https://www.cnblogs.com/wangle1001986/p/7241153.html
Copyright © 2011-2022 走看看