Search in sources :

Example 1 with HttpClientCallback

use of com.creditease.uav.httpasync.HttpClientCallback in project uavstack by uavorg.

the class SMSAction method run.

@Override
public boolean run(NotificationEvent notifyEvent) {
    // 模板关键字
    Map<String, String> keywords = new HashMap<String, String>();
    String title = notifyEvent.getTitle();
    long timeFlag = notifyEvent.getTime();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String sd = sdf.format(new Date(timeFlag));
    keywords.put("custName", sd);
    keywords.put("comName", title);
    /**
     * 若notifyEvent中包含目的地址,则用该地址;否则使用默认地址
     */
    String sms = notifyEvent.getArg(cName);
    if (StringHelper.isEmpty(sms)) {
        if (log.isTraceEnable()) {
            log.warn(this, "Send SMS FAIL as no any phone numbers.");
        }
        return false;
    }
    String[] phoneNums = sms.split(",");
    for (String phone : phoneNums) {
        List<ParaValuePair> nvps = new ArrayList<ParaValuePair>();
        // 接口版本
        nvps.add(new ParaValuePair("version", "3.0"));
        // 批次号
        nvps.add(new ParaValuePair("batchId", Long.toString(System.currentTimeMillis())));
        // 组织机构号
        nvps.add(new ParaValuePair("orgNo", "2265"));
        // 模板号
        nvps.add(new ParaValuePair("typeNo", "7209"));
        // 关键字替换
        nvps.add(new ParaValuePair("keywords", JSON.toJSONString(keywords)));
        // 手机号
        nvps.add(new ParaValuePair("mobile", phone));
        if (log.isDebugEnable()) {
            log.debug(this, "Send SMS START: phone=" + phone);
        }
        final String phoneNum = phone;
        client.doAsyncHttpPost(baseUrl + "send", nvps, "utf-8", new HttpClientCallback() {

            @Override
            public void completed(HttpClientCallbackResult result) {
                String results = result.getReplyDataAsString();
                JSONObject jo = JSON.parseObject(results);
                // 错误码
                String code = jo.getString("code");
                // 错误信息
                String desc = jo.getString("desc");
                if (log.isDebugEnable()) {
                    log.debug(this, "Send SMS END: phone=" + phoneNum + ",code=" + code + ",desc=" + desc);
                }
            }

            @Override
            public void failed(HttpClientCallbackResult result) {
                String results = result.getReplyDataAsString();
                log.err(this, "Send SMS FAIL: phone=" + phoneNum + ", result=" + results);
            }
        });
    }
    return true;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Date(java.sql.Date) HttpClientCallback(com.creditease.uav.httpasync.HttpClientCallback) ParaValuePair(com.creditease.uav.httpasync.api.ParaValuePair) JSONObject(com.alibaba.fastjson.JSONObject) HttpClientCallbackResult(com.creditease.uav.httpasync.HttpClientCallbackResult) SimpleDateFormat(java.text.SimpleDateFormat)

Example 2 with HttpClientCallback

use of com.creditease.uav.httpasync.HttpClientCallback in project uavstack by uavorg.

the class ThreadAnalysisAction method run.

@Override
public boolean run(final NotificationEvent event) {
    // 目前能够获取到线程分析地址的报警事件有:服务端:[服务状态指标系,应用状态指标系,应用服务器状态指标系],客户端:[调用状态指标系]
    // 根据event.title获取需要线程分析的server地址
    final String server = getTargetServer(event.getTitle());
    if (StringHelper.isEmpty(server)) {
        if (log.isTraceEnable()) {
            log.warn(this, "ThreadAnalysis FAILED because the event(" + event.getTitle() + ") do not support ThreadAnalysis!");
        }
        return false;
    }
    // 获取发送数据
    String data = buildRequestData(event, server);
    // 拼接线程分析命令发送地址url
    final String url = "http://" + event.getIP() + ":10101/node/ctrl";
    // 发送请求
    client.doAsyncHttpPost(url, data, new HttpClientCallback() {

        @Override
        public void completed(HttpClientCallbackResult result) {
            String results = result.getReplyDataAsString();
            @SuppressWarnings("unchecked") Map<String, String> map = JSONHelper.toObject(results, Map.class);
            String rs = map.get("rs");
            if ("OK".equals(rs)) {
                log.info(this, "ThreadAnalysis cmd send[" + url + "] SUCCEESS, [" + server + "] ThreadAnalysis result:" + results);
                sendMail(event);
            } else {
                if (log.isTraceEnable()) {
                    log.warn(this, "ThreadAnalysis cmd send[" + url + "] SUCCEESS, [" + server + "] ThreadAnalysis result:" + results);
                }
            }
        }

        @Override
        public void failed(HttpClientCallbackResult result) {
            String results = result.getReplyDataAsString();
            log.err(this, "ThreadAnalysis cmd send[" + url + "] FAILED! result:" + results, result.getException());
        }
    });
    return true;
}
Also used : HttpClientCallback(com.creditease.uav.httpasync.HttpClientCallback) HttpClientCallbackResult(com.creditease.uav.httpasync.HttpClientCallbackResult) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with HttpClientCallback

use of com.creditease.uav.httpasync.HttpClientCallback in project uavstack by uavorg.

the class DumpThreadAction method invokeJTASupporter.

private String invokeJTASupporter(final String url, final String content) {
    long start = System.currentTimeMillis();
    final CountDownLatch cdl = new CountDownLatch(1);
    final StringBuffer sb = new StringBuffer();
    httpClient.doAsyncHttpPost(url, content, new HttpClientCallback() {

        @Override
        public void completed(HttpClientCallbackResult result) {
            String res = result.getReplyDataAsString();
            if (!StringHelper.isEmpty(res) && !res.contains("ERR") && !res.contains("Err")) {
                sb.append(res);
            } else {
                log.err(this, "MOFCtrlAction process FAILED. url=" + url + ", req=" + content + ", resp=" + res);
                sb.append("ERR:MOF PROCESS FAILED:" + res);
            }
            cdl.countDown();
        }

        @Override
        public void failed(HttpClientCallbackResult result) {
            Exception e = result.getException();
            sb.append("ERR:INVOKE MOF FAILED:" + e.getMessage());
            log.err(this, "invoke MOFCtrlAction FAILED. url=" + url + ", retcode=" + result.getRetCode() + ", resp=" + result.getReplyDataAsString(), e);
            cdl.countDown();
        }
    });
    try {
        cdl.await(10000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        sb.append("ERR:INVOKE MOF TIMEOUT");
    }
    if (log.isDebugEnable()) {
        log.debug(this, "invoke MOFCtrlAction url=" + url + ", req=" + content + ", resp=" + sb.toString() + ", cost=" + (System.currentTimeMillis() - start));
    }
    return sb.toString();
}
Also used : HttpClientCallback(com.creditease.uav.httpasync.HttpClientCallback) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientCallbackResult(com.creditease.uav.httpasync.HttpClientCallbackResult)

Example 4 with HttpClientCallback

use of com.creditease.uav.httpasync.HttpClientCallback in project uavstack by uavorg.

the class HttpSystemInvoker method invoke.

/**
 * invoke
 *
 * @param serviceName
 *            服务名
 * @param serviceSubPath
 *            服务相对路径(可选)
 * @param msg
 *            提交msg对象
 * @param callback
 *            异步回调(可选)
 * @param syncTimeout
 *            同步等待超时(可选)
 * @param returnClass
 *            同步返回对象类型(可选)
 * @return
 */
private Object invoke(final String serviceName, final String serviceSubPath, final Object msg, final HttpClientCallback callback, final long syncTimeout, final Class<?> returnClass) {
    if (StringHelper.isEmpty(serviceName)) {
        return null;
    }
    // step 1: get service URI
    final ConnectionFailoverMgr cfm = this.getServiceRoute(serviceName);
    if (cfm == null) {
        throw new RuntimeException("NoSuchServiceExist:" + serviceName);
    }
    final String serviceURL = cfm.getConnection();
    if (serviceURL == null) {
        throw new RuntimeException("NoAvailableServiceInstance:" + serviceName);
    }
    String finalServiceURL = serviceURL;
    if (serviceSubPath != null) {
        finalServiceURL = serviceURL + serviceSubPath;
    }
    // step 2: convert request Object to byte
    byte[] data = null;
    // byte[]
    if (msg.getClass().isArray() && msg instanceof byte[]) {
        data = (byte[]) msg;
    } else // UAVHttpMessage
    if (UAVHttpMessage.class.isAssignableFrom(msg.getClass())) {
        try {
            data = JSONHelper.toString(msg).getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    } else // String
    if (String.class.isAssignableFrom(msg.getClass())) {
        try {
            data = msg.toString().getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    final SyncResult syncResult = new SyncResult();
    // step 3: do post invoke
    httpAsyncClient.doAsyncHttpPost(finalServiceURL, data, "application/json", "utf-8", new HttpClientCallback() {

        @Override
        public void completed(HttpClientCallbackResult result) {
            if (callback != null) {
                callback.completed(result);
            }
            if (syncTimeout <= 0) {
                return;
            }
            if (returnClass != null) {
                syncResult.setSdata(result.getReplyDataAsString());
            } else {
                syncResult.setBdata(result.getResulDataAsByteArray());
            }
        }

        @Override
        public void failed(HttpClientCallbackResult result) {
            Exception exception = result.getException();
            /**
             * Auto Failover
             */
            if (getDefFailoverCondition(exception)) {
                cfm.putFailConnection(serviceURL);
                invoke(serviceName, serviceSubPath, msg, callback);
                return;
            }
            if (callback != null) {
                callback.failed(result);
            }
            if (syncTimeout <= 0) {
                return;
            }
            HttpAsyncException excep = result.getException();
            if (excep != null) {
                syncResult.setE(excep);
            }
        }
    });
    // step 4(optional): if sync mode, we should wait
    if (syncTimeout <= 0) {
        return null;
    }
    syncResult.waitSync(syncTimeout);
    if (syncResult.getE() != null) {
        throw new RuntimeException(syncResult.getE());
    }
    if (returnClass == null) {
        return syncResult.getBdata();
    }
    if (String.class.isAssignableFrom(returnClass)) {
        return syncResult.getSdata();
    } else if (UAVHttpMessage.class.isAssignableFrom(returnClass)) {
        return new UAVHttpMessage(syncResult.getSdata());
    } else {
        return JSONHelper.toObject(syncResult.getSdata(), returnClass);
    }
}
Also used : HttpClientCallback(com.creditease.uav.httpasync.HttpClientCallback) ConnectionFailoverMgr(com.creditease.uav.helpers.connfailover.ConnectionFailoverMgr) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UAVHttpMessage(com.creditease.agent.http.api.UAVHttpMessage) HttpClientCallbackResult(com.creditease.uav.httpasync.HttpClientCallbackResult) HttpAsyncException(com.creditease.uav.httpasync.HttpAsyncException) SocketTimeoutException(java.net.SocketTimeoutException) HttpAsyncException(com.creditease.uav.httpasync.HttpAsyncException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 5 with HttpClientCallback

use of com.creditease.uav.httpasync.HttpClientCallback in project uavstack by uavorg.

the class BaseHttpMonitorDataCatchWorker method accessData.

/**
 * try to get data from UAVMOF http service
 *
 * @param serviceURL
 * @return
 * @throws IOException
 */
private String accessData(String serviceURL, String postData) throws IOException {
    final CountDownLatch wait = new CountDownLatch(1);
    final HttpDataResult hdr = new HttpDataResult();
    HttpClientCallback callback = new HttpClientCallback() {

        @Override
        public void completed(HttpClientCallbackResult result) {
            String data = result.getReplyDataAsString();
            if (!StringHelper.isEmpty(data)) {
                hdr.setData(data);
            }
            wait.countDown();
        }

        @Override
        public void failed(HttpClientCallbackResult result) {
            HttpAsyncException hae = result.getException();
            if (hae != null) {
                hdr.setE(hae.getCause());
            }
            wait.countDown();
        }
    };
    if (postData == null) {
        getHttpAsyncClient().doAsyncHttpGet(serviceURL, callback);
    } else {
        getHttpAsyncClient().doAsyncHttpPost(serviceURL, postData, callback);
    }
    // timeout for response
    try {
        wait.await(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
    // check if there is exception during http response
    if (hdr.getE() != null) {
        throw new IOException(hdr.getE());
    }
    return hdr.getData();
}
Also used : HttpClientCallback(com.creditease.uav.httpasync.HttpClientCallback) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientCallbackResult(com.creditease.uav.httpasync.HttpClientCallbackResult) HttpAsyncException(com.creditease.uav.httpasync.HttpAsyncException)

Aggregations

HttpClientCallback (com.creditease.uav.httpasync.HttpClientCallback)13 HttpClientCallbackResult (com.creditease.uav.httpasync.HttpClientCallbackResult)13 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 UAVHttpMessage (com.creditease.agent.http.api.UAVHttpMessage)5 HttpAsyncException (com.creditease.uav.httpasync.HttpAsyncException)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 JSONObject (com.alibaba.fastjson.JSONObject)1 HeartBeatEvent (com.creditease.agent.heartbeat.api.HeartBeatEvent)1 ConnectionFailoverMgr (com.creditease.uav.helpers.connfailover.ConnectionFailoverMgr)1 ParaValuePair (com.creditease.uav.httpasync.api.ParaValuePair)1 BufferedWriter (java.io.BufferedWriter)1 File (java.io.File)1 FileWriter (java.io.FileWriter)1 SocketTimeoutException (java.net.SocketTimeoutException)1 Date (java.sql.Date)1 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1