Search in sources :

Example 6 with HttpClientCallback

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

the class NotificaitonScheduleWorker method executeHttpCommand.

public void executeHttpCommand(String url, String content) {
    byte[] datab = null;
    try {
        datab = content.getBytes("utf-8");
    } catch (UnsupportedEncodingException e) {
        return;
    }
    HttpAsyncClient.instance().doAsyncHttpPost(url, datab, "application/json", "utf-8", new HttpClientCallback() {

        @Override
        public void completed(HttpClientCallbackResult result) {
            String results = result.getReplyDataAsString();
            log.info(this, "getReplyDataAsString. \n" + results);
            log.info(this, "getReplyData. \n" + result.getReplyData());
        }

        @Override
        public void failed(HttpClientCallbackResult result) {
            log.info(this, "failed. \n");
        }
    });
}
Also used : HttpClientCallback(com.creditease.uav.httpasync.HttpClientCallback) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpClientCallbackResult(com.creditease.uav.httpasync.HttpClientCallbackResult)

Example 7 with HttpClientCallback

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

the class HttpTestQuery method executeHttpCommand.

public static void executeHttpCommand(final String fileName, String url, String content) {
    byte[] datab = null;
    try {
        datab = content.getBytes("utf-8");
    } catch (UnsupportedEncodingException e) {
        return;
    }
    HttpAsyncClient.instance().doAsyncHttpPost(url, datab, "application/json", "utf-8", new HttpClientCallback() {

        @Override
        public void completed(HttpClientCallbackResult result) {
            String results = result.getReplyDataAsString();
            LOG.info("getReplyDataAsString. \n" + results);
            LOG.info("getReplyData. \n" + result.getReplyData());
            try {
                BufferedWriter writer = null;
                try {
                    File file = new File("logs/" + fileName + ".query");
                    System.out.println("filename:::::::::::::::::::" + fileName);
                    writer = new BufferedWriter(new FileWriter(file));
                    writer.write(results);
                } catch (IOException e) {
                } finally {
                    writer.flush();
                    writer.close();
                }
            } catch (IOException e) {
            }
        }

        @Override
        public void failed(HttpClientCallbackResult result) {
            LOG.info("failed. \n");
        }
    });
}
Also used : HttpClientCallback(com.creditease.uav.httpasync.HttpClientCallback) FileWriter(java.io.FileWriter) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) HttpClientCallbackResult(com.creditease.uav.httpasync.HttpClientCallbackResult) File(java.io.File) BufferedWriter(java.io.BufferedWriter)

Example 8 with HttpClientCallback

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

the class NodeOperCtrlClient method doCMD.

private static void doCMD(final String cmd, Map<String, String> jsonArgs, String port) {
    UAVHttpMessage msg = new UAVHttpMessage();
    msg.setIntent(cmd);
    for (String key : jsonArgs.keySet()) {
        msg.putRequest(key, jsonArgs.get(key));
    }
    HttpAsyncClient.build(5, 5);
    String url = "http://localhost:" + port + "/node/ctrl";
    print("Node Operation Command[" + cmd + "] START on " + url);
    HttpAsyncClient.instance().doAsyncHttpPost(url, JSONHelper.toString(msg), new HttpClientCallback() {

        @Override
        public void completed(HttpClientCallbackResult result) {
            print("Node Operation Command[" + cmd + "] DONE.");
            System.exit(0);
        }

        @Override
        public void failed(HttpClientCallbackResult result) {
            print("Node Operation Command[" + cmd + "] DONE.");
            System.exit(0);
        }
    });
}
Also used : HttpClientCallback(com.creditease.uav.httpasync.HttpClientCallback) UAVHttpMessage(com.creditease.agent.http.api.UAVHttpMessage) HttpClientCallbackResult(com.creditease.uav.httpasync.HttpClientCallbackResult)

Example 9 with HttpClientCallback

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

the class MOFCtrlAction method doAction.

@Override
public void doAction(ActionContext context) throws Exception {
    UAVHttpMessage data = (UAVHttpMessage) context.getParam("msg");
    /**
     * Step 1: start the Supporter (AutoCheck if it is started)
     */
    String action = data.getRequest("action");
    String server = data.getRequest("server") + "/com.creditease.uav/server?action=" + action;
    String rootPath = data.getRequest("root");
    if (!StringHelper.isEmpty(rootPath)) {
        server += "&tag=" + rootPath;
    }
    final String url = server;
    String param = data.getRequest("actparam");
    final AtomicBoolean isSuccess = new AtomicBoolean(false);
    final CountDownLatch cdl = new CountDownLatch(1);
    final StringBuilder response = new StringBuilder();
    client.doAsyncHttpPost(url, param, new HttpClientCallback() {

        @Override
        public void completed(HttpClientCallbackResult result) {
            String res = result.getReplyDataAsString();
            if (result.getRetCode() >= 400) {
                log.err(this, "MOFCtrlAction FAIL: retcode=" + result.getRetCode() + ", url=" + url + ", err=" + res);
                if (result.getRetCode() >= 500) {
                    response.append("请求" + url + "完成时的状态码为【" + result.getRetCode() + "】, 服务器遇到错误而不能完成该请求.");
                } else {
                    response.append("请求" + url + "完成时的状态码为【" + result.getRetCode() + "】, 请求客户端错误.");
                }
                isSuccess.set(false);
            } else {
                response.append(res);
                log.info(this, "MOFCtrlAction Success: retcode=" + result.getRetCode() + ", url=" + url + ", res=" + res);
                if (!StringHelper.isEmpty(res)) {
                    isSuccess.set(true);
                }
            }
            cdl.countDown();
        }

        @Override
        public void failed(HttpClientCallbackResult result) {
            String exp = result.getException().getMessage();
            response.append(exp);
            log.err(this, "MOFCtrlAction FAIL: url=" + url + ", err=" + exp);
            isSuccess.set(false);
            cdl.countDown();
        }
    });
    cdl.await(5000, TimeUnit.MILLISECONDS);
    if (isSuccess.get() == false) {
        data.putResponse("rs", "ERR");
        data.putResponse("msg", response.toString());
        return;
    }
    /**
     * Step 2: notify Collect Client for capture files
     */
    if (data.getRequest().containsKey("collectact")) {
        doCollectFiles(data, response, rootPath);
        return;
    }
    data.putResponse("rs", "OK");
    data.putResponse("msg", response.toString());
}
Also used : HttpClientCallback(com.creditease.uav.httpasync.HttpClientCallback) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) UAVHttpMessage(com.creditease.agent.http.api.UAVHttpMessage) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientCallbackResult(com.creditease.uav.httpasync.HttpClientCallbackResult)

Example 10 with HttpClientCallback

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

the class HeartBeatClientReqWorker method doServiceDiscovery.

/**
 * 实现服务发现功能:MSCP的服务发现需要利用心跳客户端的支持
 *
 * @param serviceName
 * @return
 */
public String[] doServiceDiscovery(String serviceName) {
    /**
     * step 1: select a heartbeat server url
     */
    final String connectStr = cfmgr.getConnection();
    if (null == connectStr) {
        log.err(this, "Select HeartBeatServer URL Fail as no available HeartBeatServer.");
        return null;
    }
    String[] connectInfo = connectStr.split(":");
    /**
     * NOTE: hbQueryServer's port=hbServer's port +10
     */
    int hbServerPort = DataConvertHelper.toInt(connectInfo[1], 8010) + 10;
    String hbserverURL = "http://" + connectInfo[0] + ":" + hbServerPort + "/hb/query";
    if (log.isDebugEnable()) {
        log.debug(this, "Selected HeartBeatServer URL is " + hbserverURL);
    }
    /**
     * step 2: build msg
     */
    UAVHttpMessage msg = new UAVHttpMessage();
    msg.setIntent("services");
    msg.putRequest("service", serviceName);
    byte[] datab = null;
    try {
        datab = JSONHelper.toString(msg).getBytes("utf-8");
    } catch (UnsupportedEncodingException e1) {
        return null;
    }
    /**
     * step 3: request hbquery
     */
    final CountDownLatch cdl = new CountDownLatch(1);
    final StringBuffer resultStr = new StringBuffer();
    client.doAsyncHttpPost(hbserverURL, datab, "application/json", "utf-8", new HttpClientCallback() {

        @Override
        public void completed(HttpClientCallbackResult result) {
            /**
             * step 4: run handlers for downstream response
             */
            resultStr.append(result.getReplyDataAsString());
            // CountDownLatch unlock
            cdl.countDown();
        }

        @Override
        public void failed(HttpClientCallbackResult result) {
            /**
             * mark this hbserver is NOT OK
             */
            cfmgr.putFailConnection(connectStr);
            // CountDownLatch unlock
            cdl.countDown();
        }
    });
    /**
     * step 4: wait the async http invoking result
     */
    try {
        cdl.await(5000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
    // ignore
    }
    if (resultStr.length() == 0) {
        return null;
    }
    @SuppressWarnings("unchecked") Map<String, String> resMap = JSONHelper.toObject(resultStr.toString(), Map.class);
    if (resMap.containsKey("err")) {
        return null;
    }
    String servicesStr = resMap.get("rs");
    List<String> services = JSONHelper.toObjectArray(servicesStr, String.class);
    String[] urls = new String[services.size()];
    return services.toArray(urls);
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) UAVHttpMessage(com.creditease.agent.http.api.UAVHttpMessage) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientCallback(com.creditease.uav.httpasync.HttpClientCallback) HttpClientCallbackResult(com.creditease.uav.httpasync.HttpClientCallbackResult)

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