Search in sources :

Example 1 with UnitResponse

use of info.xiancloud.core.message.UnitResponse in project xian by happyyangyuan.

the class App method main.

public static void main(String[] args) {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("subDec", " * some third access \r\n\r\n * appId=e8249b116f5efa7c67ab1e7c79d8ba02cbe2451a,appSecret=另行邮件通知 \r\n\r\n  除获取token接口外,其他接口必须传入header:xian-accessToken=<yourToken>\r\n");
    params.put("docName", "接口文档");
    // params.put("path", "test");
    // "[{'apiBuildService':['apiDocUnit']}]"
    params.put("unitFilter", "apiBuildService.apiDocUnit");
    Xian.call("apiBuildService", "apiDocUnit", params, new NotifyHandler() {

        @Override
        protected void handle(UnitResponse unitResponse) {
            System.out.println(unitResponse.toString());
        }
    });
}
Also used : HashMap(java.util.HashMap) UnitResponse(info.xiancloud.core.message.UnitResponse) NotifyHandler(info.xiancloud.core.NotifyHandler)

Example 2 with UnitResponse

use of info.xiancloud.core.message.UnitResponse in project xian by happyyangyuan.

the class BatchUnit method execute.

/**
 * 组件业务执行方法
 *
 * @param msg 具体的消息
 */
public UnitResponse execute(UnitRequest msg) {
    UnitResponse result;
    // 是否马上提交
    boolean flush = msg.get(FLUSH, Boolean.class, false);
    msg.getArgMap().remove(FLUSH);
    // 判断是否需要批量操作
    if (getBatchSize() >= MIN_BATCH_SIZE) {
        recordCacheList.add(msg.getArgMap());
        // 判断是否达到批量执行的数量阈值,或者业务需要立即执行
        if (recordCacheList.size() >= getBatchSize() || flush) {
            Map<String, Object> params = new HashMap<>();
            synchronized (recordCacheList) {
                params.put(VALUES, new ArrayList<Map>(recordCacheList));
                recordCacheList.clear();
            }
            preBatchExecute(msg);
            result = SyncXian.call(getBatchGroupName(), getBatchUnitName(), params);
        } else {
            result = doCache(msg);
        }
    } else {
        // 没有批量需求,立即执行
        result = SyncXian.call(getBatchGroupName(), getBatchUnitName(), msg.getArgMap());
    }
    return result;
}
Also used : UnitResponse(info.xiancloud.core.message.UnitResponse)

Example 3 with UnitResponse

use of info.xiancloud.core.message.UnitResponse in project xian by happyyangyuan.

the class AbstractAction method execute.

public UnitResponse execute(Unit daoUnit, Map map, Connection connection) {
    this.map = map;
    this.connection = connection;
    this.daoUnit = (DaoUnit) daoUnit;
    putLastAutoGeneratedValueIntoMap();
    if (ignore(map, this.daoUnit, connection)) {
        return UnitResponse.success(String.format("此sql action '%s.%s' 被忽略", this.daoUnit.getName(), getClass().getSimpleName()));
    }
    UnitResponse checkUnitResponse = check(daoUnit, map, connection);
    if (!checkUnitResponse.getCode().equals(Group.CODE_SUCCESS)) {
        return checkUnitResponse;
    }
    try {
        logSql(map);
        return UnitResponse.success(executeSql(getPreparedSQL(), getSqlParams(), connection));
    } catch (SQLException e) {
        LOG.error("", e);
        String actualSql = null;
        try {
            actualSql = SqlUtils.mapToSql(getSqlPattern(), map);
        } catch (SQLException e1) {
            LOG.error("", e1);
        }
        switch(e.getErrorCode()) {
            case 1062:
                /**
                 *Error: 1062 SQLSTATE: 23000 (ER_DUP_ENTRY)
                 *                     Message: Duplicate entry '%s' for key %d *
                 */
                return UnitResponse.create(DaoGroup.CODE_REPETITION_NOT_ALLOWED, map, e.getLocalizedMessage());
            default:
                return UnitResponse.error(DaoGroup.CODE_SQL_ERROR, actualSql, "执行sql语句出现问题");
        }
    }
}
Also used : SQLException(java.sql.SQLException) UnitResponse(info.xiancloud.core.message.UnitResponse)

Example 4 with UnitResponse

use of info.xiancloud.core.message.UnitResponse in project xian by happyyangyuan.

the class Request method execute.

/**
 * 调用unit执行
 *
 * @throws IOException IOException
 */
public String execute() throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(this);
    oos.flush();
    String reqBase64 = new String(Base64.getEncoder().encode(bos.toByteArray()));
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("req", reqBase64);
    UnitResponse out = SyncXian.call("httpClient", "http", map);
    if (out.succeeded()) {
        return out.dataToJson().getString("entity");
    } else {
        switch(out.getCode()) {
            case ISocketGroup.CODE_CONNECT_TIMEOUT:
                throw new ConnectException("连接超时:" + url);
            case ISocketGroup.CODE_SOCKET_TIMEOUT:
                throw new SocketTimeoutException("响应超时:" + url);
            default:
                throw new RuntimeException("请求失败:" + url);
        }
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) HashMap(java.util.HashMap) UnitResponse(info.xiancloud.core.message.UnitResponse) ConnectException(java.net.ConnectException)

Example 5 with UnitResponse

use of info.xiancloud.core.message.UnitResponse in project xian by happyyangyuan.

the class AbstractAsyncForwarder method forward.

@Override
public void forward(String uri, String ip, String msgId, Map<String, String> header, String body) {
    LOG.debug("this method is running in the netty http server's io thread.");
    UnitRequest controllerRequest;
    try {
        controllerRequest = bodyParams(body, header);
    } catch (BadRequestException badRequestException) {
        LOG.warn(badRequestException);
        ServerResponseBean responseBean = new ServerResponseBean();
        responseBean.setMsgId(msgId);
        responseBean.setHttpContentType(HttpContentType.APPLICATION_JSON);
        responseBean.setResponseBody(UnitResponse.error(Group.CODE_BAD_REQUEST, null, badRequestException.getLocalizedMessage()).toVoJSONString());
        IServerResponder.singleton.response(responseBean);
        return;
    }
    RequestContext context = controllerRequest.getContext();
    URIBean uriBean = URIBean.create(uri);
    context.setUri(uri).setIp(ip).setHeader(header).setUnit(uriBean.getUnit()).setGroup(uriBean.getGroup()).setUriExtension(uriBean.getUriExtension()).setMsgId(msgId).setUriParameters(uriBean.getUriParameters());
    // uri parameters overwrite body parameters.
    controllerRequest.getArgMap().putAll(uriBean.getUriParameters());
    BaseController controller = IControllerMapping.getController(controllerRequest, new TransactionalNotifyHandler() {

        protected void handle(UnitResponse unitResponse) {
            if (unitResponse == null) {
                Throwable emptyOutputException = new RuntimeException("UnitResponse is not allowed to be null.");
                LOG.error(emptyOutputException);
                unitResponse = UnitResponse.exception(emptyOutputException);
            } else if (StringUtil.isEmpty(unitResponse.getCode())) {
                Throwable emptyOutputException = new RuntimeException("UnitResponse's code is not allowed to be empty: " + unitResponse);
                LOG.error(emptyOutputException);
                unitResponse = UnitResponse.exception(emptyOutputException);
            }
            ServerResponseBean responseBean = new ServerResponseBean();
            responseBean.setResponseBody(extractContext(unitResponse));
            responseBean.setMsgId(msgId);
            responseBean.setHttpContentType(unitResponse.getContext().getHttpContentType());
            IServerResponder.singleton.response(responseBean);
        }
    });
    ThreadPoolManager.execute(controller, msgId);
}
Also used : UnitRequest(info.xiancloud.core.message.UnitRequest) BaseController(info.xiancloud.gateway.executor.BaseController) UnitResponse(info.xiancloud.core.message.UnitResponse) BadRequestException(info.xiancloud.core.distribution.exception.BadRequestException) ServerResponseBean(info.xiancloud.gateway.server.ServerResponseBean) TransactionalNotifyHandler(info.xiancloud.gateway.handle.TransactionalNotifyHandler) RequestContext(info.xiancloud.core.message.RequestContext) URIBean(info.xiancloud.gateway.executor.URIBean)

Aggregations

UnitResponse (info.xiancloud.core.message.UnitResponse)106 JSONObject (com.alibaba.fastjson.JSONObject)74 HashMap (java.util.HashMap)22 UnitRequest (info.xiancloud.core.message.UnitRequest)17 NotifyHandler (info.xiancloud.core.NotifyHandler)16 JSONArray (com.alibaba.fastjson.JSONArray)9 Unit (info.xiancloud.core.Unit)6 UnitMeta (info.xiancloud.core.UnitMeta)6 CacheGroup (info.xiancloud.cache.service.CacheGroup)5 Group (info.xiancloud.core.Group)5 Input (info.xiancloud.core.Input)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 Redis (info.xiancloud.cache.redis.Redis)4 CacheConfigBean (info.xiancloud.core.support.cache.CacheConfigBean)4 ThreadPoolManager (info.xiancloud.core.thread_pool.ThreadPoolManager)3 LOG (info.xiancloud.core.util.LOG)3 Set (java.util.Set)3 Test (org.junit.Test)3 MessageType (info.xiancloud.core.distribution.MessageType)2 UnitUndefinedException (info.xiancloud.core.distribution.exception.UnitUndefinedException)2