Search in sources :

Example 1 with HttpAsyncException

use of com.creditease.uav.httpasync.HttpAsyncException 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 2 with HttpAsyncException

use of com.creditease.uav.httpasync.HttpAsyncException 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)

Example 3 with HttpAsyncException

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

the class HeartBeatClientReqWorker method handleResponse.

protected void handleResponse(HeartBeatEventClientWorker hbEventClientWorker, HttpClientCallbackResult result) {
    /**
     * step 4.1: check if there is exception
     */
    HttpAsyncException hae = result.getException();
    if (null != hae) {
        log.err(this, "Receive HeartBeatClientEvent Fail: StatusCode=" + result.getRetCode() + ",ExceptionEvent=" + hae.getExceptionEvent(), hae.getCause());
        return;
    }
    /**
     * step 4.2: put the HeartBeatClientEvent into downstream queue
     */
    String respStr = result.getReplyDataAsString();
    HeartBeatEvent respEvent = new HeartBeatEvent(Stage.CLIENT_IN, respStr);
    respEvent.setStage(Stage.CLIENT_IN);
    hbEventClientWorker.putData(respEvent);
}
Also used : HeartBeatEvent(com.creditease.agent.heartbeat.api.HeartBeatEvent) HttpAsyncException(com.creditease.uav.httpasync.HttpAsyncException)

Example 4 with HttpAsyncException

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

the class AppHubBaseRestService method doHttpPost.

/**
 * 支持普通Http Post调用和智能的带FailOver的调用
 *
 * @param postUrl
 * @param subPath
 * @param data
 * @param contentType
 * @param encoding
 * @param callBack
 */
public void doHttpPost(String serverAddress, String subPath, byte[] data, String contentType, String encoding, HttpClientCallback callBack) {
    ConnectionFailoverMgr cfm = httpConnInvokeMgr.get(serverAddress);
    /**
     * Step 1: if there is no ConnectionFailoverMgr, take it as normal http post
     */
    if (cfm == null) {
        final String postURL = (subPath != null) ? (serverAddress + subPath) : serverAddress;
        httpAsyncClient.doAsyncHttpPost(postURL, data, contentType, encoding, callBack);
        return;
    }
    /**
     * Step 2: do smart http post
     */
    String url = cfm.getConnection();
    if (url == null) {
        String msg = "No Available Address for ServerAddressList[" + serverAddress + "]";
        this.getLogger().warn(this, msg);
        if (callBack != null) {
            HttpClientCallbackResult result = new HttpClientCallbackResult(null, null);
            result.setException(new HttpAsyncException(ExceptionEvent.REPLY_ERROR, new ConnectException(msg)));
            callBack.failed(result);
        }
        return;
    }
    String postURL = (subPath != null) ? (url + subPath) : url;
    getLogger().info(this, "doHttpPost URL :" + postURL);
    PostHttpCallback postHttpCb = new PostHttpCallback();
    postHttpCb.setCallBack(callBack);
    postHttpCb.setCfm(cfm);
    postHttpCb.setContentType(contentType);
    postHttpCb.setData(data);
    postHttpCb.setEncoding(encoding);
    postHttpCb.setPostURL(postURL);
    postHttpCb.setServerAddress(serverAddress);
    postHttpCb.setSubPath(subPath);
    postHttpCb.setUrl(url);
    httpAsyncClient.doAsyncHttpPost(postURL, data, contentType, encoding, postHttpCb);
}
Also used : ConnectionFailoverMgr(com.creditease.uav.helpers.connfailover.ConnectionFailoverMgr) HttpClientCallbackResult(com.creditease.uav.httpasync.HttpClientCallbackResult) HttpAsyncException(com.creditease.uav.httpasync.HttpAsyncException) ConnectException(java.net.ConnectException)

Aggregations

HttpAsyncException (com.creditease.uav.httpasync.HttpAsyncException)4 HttpClientCallbackResult (com.creditease.uav.httpasync.HttpClientCallbackResult)3 ConnectionFailoverMgr (com.creditease.uav.helpers.connfailover.ConnectionFailoverMgr)2 HttpClientCallback (com.creditease.uav.httpasync.HttpClientCallback)2 HeartBeatEvent (com.creditease.agent.heartbeat.api.HeartBeatEvent)1 UAVHttpMessage (com.creditease.agent.http.api.UAVHttpMessage)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 ConnectException (java.net.ConnectException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 CountDownLatch (java.util.concurrent.CountDownLatch)1