Search in sources :

Example 26 with JeesuiteBaseException

use of com.jeesuite.common.JeesuiteBaseException in project jeesuite-libs by vakinge.

the class MQServiceRegistryBean method startConsumer.

private void startConsumer(String providerName) throws Exception {
    Map<String, MessageHandler> messageHanlders = applicationContext.getBeansOfType(MessageHandler.class);
    if (messageHanlders != null && !messageHanlders.isEmpty()) {
        Map<String, MessageHandler> messageHandlerMaps = new HashMap<>();
        messageHanlders.values().forEach(e -> {
            Object origin = e;
            try {
                origin = SpringAopHelper.getTarget(e);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            MQTopicRef topicRef = origin.getClass().getAnnotation(MQTopicRef.class);
            String topicName = MQContext.rebuildWithNamespace(topicRef.value());
            messageHandlerMaps.put(topicName, e);
            logger.info("ADD MQ_COMSUMER_HANDLER ->topic:{},handlerClass:{} ", topicName, e.getClass().getName());
        });
        if ("rocketmq".equals(providerName)) {
            consumer = new RocketmqConsumerAdapter(messageHandlerMaps);
        } else if ("cmq".equals(providerName)) {
            consumer = new CMQConsumerAdapter(messageHandlerMaps);
        } else if ("memoryqueue".equals(providerName)) {
            MemoryQueueProducerAdapter.setMessageHandlers(messageHandlerMaps);
        } else {
            throw new JeesuiteBaseException("NOT_SUPPORT[providerName]:" + providerName);
        }
        consumer.start();
        logger.info("MQ_COMSUMER started -> groupName:{},providerName:{}", MQContext.getGroupName(), providerName);
    }
}
Also used : JeesuiteBaseException(com.jeesuite.common.JeesuiteBaseException) HashMap(java.util.HashMap) CMQConsumerAdapter(com.jeesuite.amqp.qcloud.cmq.CMQConsumerAdapter) RocketmqConsumerAdapter(com.jeesuite.amqp.rocketmq.RocketmqConsumerAdapter) BeansException(org.springframework.beans.BeansException) JeesuiteBaseException(com.jeesuite.common.JeesuiteBaseException)

Example 27 with JeesuiteBaseException

use of com.jeesuite.common.JeesuiteBaseException in project jeesuite-libs by vakinge.

the class GenericApiRequest method postJSON.

public static String postJSON(String url, String json) {
    RequestBody requestBody = FormBody.create(JSON_MEDIA_TYPE, json);
    Request request = new Request.Builder().url(url).post(requestBody).build();
    try {
        Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        }
        String message = response.message();
        if (StringUtils.isBlank(message)) {
            message = HttpStatus.valueOf(response.code()).getReasonPhrase();
        }
        if (logger.isDebugEnabled())
            logger.debug("call_remote_api_error ->url:{},code:{},message:{}", url, response.code(), message);
        throw new JeesuiteBaseException(response.code(), message);
    } catch (Exception e) {
        logger.error("调用远程服务失败[" + url + "]", e);
        throw new JeesuiteBaseException("系统繁忙,稍后再试[004]");
    }
}
Also used : Response(okhttp3.Response) JeesuiteBaseException(com.jeesuite.common.JeesuiteBaseException) Request(okhttp3.Request) JeesuiteBaseException(com.jeesuite.common.JeesuiteBaseException) RequestBody(okhttp3.RequestBody)

Example 28 with JeesuiteBaseException

use of com.jeesuite.common.JeesuiteBaseException in project jeesuite-libs by vakinge.

the class GenericApiRequest method execute.

private String execute() {
    String url = CustomRequestHostHolder.resolveUrl(requestUrl);
    HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
    if (requestParameters != null) {
        for (String key : requestParameters.keySet()) {
            urlBuilder.addQueryParameter(key, requestParameters.get(key).toString());
        }
    }
    okhttp3.Headers.Builder headerBuilder = new Headers.Builder();
    Map<String, String> customHeaders = RequestHeaderBuilder.getHeaders();
    if (headers != null) {
        customHeaders.putAll(headers);
    }
    customHeaders.forEach((name, value) -> {
        headerBuilder.add(name, value);
    });
    // 标记不需要封装
    headerBuilder.add(CustomRequestHeaders.HEADER_RESP_KEEP, Boolean.TRUE.toString());
    okhttp3.Request.Builder requestBuilder = new Request.Builder().headers(headerBuilder.build()).url(urlBuilder.build());
    String postJson = null;
    if (requestMethod == HttpMethod.POST && requestData != null) {
        RequestBody body;
        if (JSON_MEDIA_TYPE.equals(mediaType)) {
            postJson = (requestData instanceof String) ? requestData.toString() : JsonUtils.toJson(requestData);
            body = FormBody.create(JSON_MEDIA_TYPE, postJson);
        } else {
            Map<String, Object> requestDataMap;
            if (requestData instanceof Map) {
                requestDataMap = (Map<String, Object>) requestData;
            } else {
                requestDataMap = BeanUtils.beanToMap(requestData);
            }
            FormBody.Builder builder = new FormBody.Builder();
            requestDataMap.forEach((k, v) -> {
                if (v != null)
                    builder.add(k, v.toString());
            });
            body = builder.build();
        }
        requestBuilder.post(body);
    }
    if (logger.isDebugEnabled()) {
        StringBuilder logData = new StringBuilder();
        logData.append("------call_remote_api_begin------\n");
        logData.append("url:").append(url).append("\n");
        logData.append("method:").append(requestMethod.name()).append("\n");
        if (postJson != null)
            logData.append("requestData:").append(postJson).append("\n");
        logger.debug(logData.toString());
    }
    String responseString = null;
    try {
        Response response = httpClient.newCall(requestBuilder.build()).execute();
        if (response.body() != null) {
            responseString = StringUtils.trimToNull(response.body().string());
            if (responseString == null)
                return null;
            if (responseString.startsWith(STANDARD_RSP_JSON_PREFIX)) {
                JSONObject jsonObject = JSON.parseObject(responseString);
                int code = jsonObject.getIntValue(GlobalConstants.PARAM_CODE);
                if (code == 200) {
                    responseString = jsonObject.getString(GlobalConstants.PARAM_DATA);
                } else {
                    if (logger.isDebugEnabled())
                        logger.debug("call_remote_api_error ->url:{},code:{},message:{}", url, code, jsonObject.getString("msg"));
                    throw new JeesuiteBaseException(code, jsonObject.getString("msg"));
                }
            } else if (responseString.startsWith(OPENGW_ERROR_RSP_JSON_PREFIX)) {
                JSONObject jsonObject = JSON.parseObject(responseString);
                throw new JeesuiteBaseException(jsonObject.getString("msg"));
            }
        }
        if (response.isSuccessful()) {
            return responseString;
        } else if (response.isRedirect()) {
            throw new JeesuiteBaseException(302, response.message());
        } else {
            String message = response.message();
            if (StringUtils.isBlank(message)) {
                message = HttpStatus.valueOf(response.code()).getReasonPhrase();
            }
            if (logger.isDebugEnabled())
                logger.debug("call_remote_api_error ->url:{},code:{},message:{}", url, response.code(), message);
            throw new JeesuiteBaseException(response.code(), message);
        }
    } catch (Exception e) {
        StringBuilder errorMessage = new StringBuilder();
        errorMessage.append("------call_remote_api_error------\n");
        errorMessage.append("url:").append(url).append("\n");
        errorMessage.append("method:").append(requestMethod.name()).append("\n");
        if (responseString != null)
            errorMessage.append("responseData:").append(responseString).append("\n");
        errorMessage.append("error:").append(e.getMessage());
        logger.error(errorMessage.toString());
        if (e instanceof JeesuiteBaseException)
            throw (JeesuiteBaseException) e;
        if (e instanceof java.net.SocketTimeoutException) {
            throw new JeesuiteBaseException(504, e.getMessage());
        }
        throw new JeesuiteBaseException("系统繁忙,稍后再试[004]");
    }
}
Also used : Headers(okhttp3.Headers) CustomRequestHeaders(com.jeesuite.common.CustomRequestHeaders) Request(okhttp3.Request) FormBody(okhttp3.FormBody) HttpUrl(okhttp3.HttpUrl) JeesuiteBaseException(com.jeesuite.common.JeesuiteBaseException) Response(okhttp3.Response) JSONObject(com.alibaba.fastjson.JSONObject) JeesuiteBaseException(com.jeesuite.common.JeesuiteBaseException) JSONObject(com.alibaba.fastjson.JSONObject) HashMap(java.util.HashMap) Map(java.util.Map) RequestBody(okhttp3.RequestBody)

Example 29 with JeesuiteBaseException

use of com.jeesuite.common.JeesuiteBaseException in project jeesuite-libs by vakinge.

the class CustomResponseErrorHandler method handleError.

@Override
public void handleError(ClientHttpResponse response) throws IOException {
    int code = response.getRawStatusCode();
    String content = CharStreams.toString(new InputStreamReader(response.getBody(), StandardCharsets.UTF_8));
    Map<?, ?> responseItmes = null;
    if (code == 404 && StringUtils.isNotBlank(content)) {
        responseItmes = JsonUtils.toObject(content, Map.class);
        throw new JeesuiteBaseException(404, "Page Not Found[" + responseItmes.get("path") + "]");
    }
    int errorCode = 500;
    String errorMsg = content;
    try {
        responseItmes = JsonUtils.toObject(content, Map.class);
    } catch (Exception e) {
    }
    if (responseItmes != null) {
        if (responseItmes.containsKey("code")) {
            errorCode = Integer.parseInt(responseItmes.get("code").toString());
        }
        if (responseItmes.containsKey("msg")) {
            errorMsg = responseItmes.get("msg").toString();
        } else if (responseItmes.containsKey("message")) {
            errorMsg = responseItmes.get("message").toString();
        }
    }
    if (StringUtils.isBlank(errorMsg)) {
        errorMsg = DEFAULT_ERROR_MSG;
    }
    throw new JeesuiteBaseException(errorCode, errorMsg + "(Remote)");
}
Also used : InputStreamReader(java.io.InputStreamReader) JeesuiteBaseException(com.jeesuite.common.JeesuiteBaseException) Map(java.util.Map) IOException(java.io.IOException) JeesuiteBaseException(com.jeesuite.common.JeesuiteBaseException)

Example 30 with JeesuiteBaseException

use of com.jeesuite.common.JeesuiteBaseException in project jeesuite-libs by vakinge.

the class QiniuProvider method getObjectBytes.

@Override
public byte[] getObjectBytes(String bucketName, String fileKey) {
    bucketName = buildBucketName(bucketName);
    String downloadUrl = getDownloadUrl(bucketName, fileKey, 600);
    Request request = new Request.Builder().url(downloadUrl).build();
    okhttp3.Response re = null;
    try {
        re = httpClient.newCall(request).execute();
        if (re.isSuccessful()) {
            return re.body().bytes();
        }
        throw new JeesuiteBaseException(re.code(), re.message());
    } catch (IOException e) {
        throw new JeesuiteBaseException(e.getMessage());
    }
}
Also used : JeesuiteBaseException(com.jeesuite.common.JeesuiteBaseException) Request(okhttp3.Request) IOException(java.io.IOException)

Aggregations

JeesuiteBaseException (com.jeesuite.common.JeesuiteBaseException)41 IOException (java.io.IOException)14 Request (okhttp3.Request)7 CosServiceException (com.qcloud.cos.exception.CosServiceException)4 CObjectMetadata (com.jeesuite.cos.CObjectMetadata)3 InputStream (java.io.InputStream)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 InvalidKeyException (java.security.InvalidKeyException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 SignatureException (java.security.SignatureException)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 CUploadResult (com.jeesuite.cos.CUploadResult)2 WrapperResponseEntity (com.jeesuite.springweb.model.WrapperResponseEntity)2 COSObject (com.qcloud.cos.model.COSObject)2 ObjectMetadata (com.qcloud.cos.model.ObjectMetadata)2 QiniuException (com.qiniu.common.QiniuException)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 FileOutputStream (java.io.FileOutputStream)2