Search in sources :

Example 21 with JeesuiteBaseException

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

the class GlobalExceptionHandler method exceptionHandler.

@ExceptionHandler(Exception.class)
@ResponseBody
public WrapperResponse<?> exceptionHandler(Exception e, HttpServletResponse response) {
    // 缓存回滚
    if (rollbackCacheMethod != null) {
        try {
            rollbackCacheMethod.invoke(null);
        } catch (Exception e2) {
        }
    }
    WrapperResponse<?> resp = new WrapperResponse<>();
    e = (Exception) getActualThrowable(e);
    if (e instanceof JeesuiteBaseException) {
        JeesuiteBaseException e1 = (JeesuiteBaseException) e;
        resp.setCode(e1.getCode());
        resp.setMsg(e1.getMessage());
    } else if (e instanceof org.springframework.web.HttpRequestMethodNotSupportedException) {
        resp.setCode(HttpStatus.METHOD_NOT_ALLOWED.value());
        resp.setMsg(e.getMessage());
    } else if (e instanceof org.springframework.web.HttpMediaTypeException) {
        resp.setCode(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value());
        resp.setMsg(e.getMessage());
    } else if (e instanceof org.springframework.web.bind.MissingServletRequestParameterException) {
        resp.setCode(1001);
        resp.setMsg(e.getMessage());
    } else if (e instanceof MethodArgumentNotValidException) {
        resp.setCode(400);
        List<ObjectError> errors = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors();
        String fieldName;
        StringBuilder fieldNames = new StringBuilder();
        for (ObjectError error : errors) {
            String errMsg = error.getDefaultMessage();
            fieldName = parseFieldName(error);
            fieldNames.append(fieldName).append(",");
        }
        resp.setBizCode("error.parameter.notValid");
        resp.setMsg("参数错误[" + fieldNames.toString() + "]");
    } else {
        Throwable parent = e.getCause();
        if (parent instanceof IllegalStateException) {
            resp.setCode(501);
            resp.setMsg(e.getMessage());
        } else {
            resp.setCode(500);
            resp.setMsg("系统繁忙");
        }
    }
    // 默认情况http code都转换为200,异常信息由异常体传递
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    if (request != null && Boolean.parseBoolean(request.getHeader(CustomRequestHeaders.HEADER_HTTP_STATUS_KEEP))) {
        int errorCode = resp.getCode();
        if (errorCode >= 400 && errorCode <= 500) {
            response.setStatus(errorCode);
        } else {
            response.setStatus(500);
        }
    }
    response.addIntHeader(CustomRequestHeaders.HEADER_EXCEPTION_CODE, resp.getCode());
    response.addHeader(CustomRequestHeaders.HEADER_RESP_KEEP, Boolean.TRUE.toString());
    // 
    ActionLogCollector.onResponseEnd(response.getStatus(), e);
    return resp;
}
Also used : ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) JeesuiteBaseException(com.mendmix.common.JeesuiteBaseException) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) HttpServletRequest(javax.servlet.http.HttpServletRequest) WrapperResponse(com.mendmix.common.model.WrapperResponse) ObjectError(org.springframework.validation.ObjectError) JeesuiteBaseException(com.mendmix.common.JeesuiteBaseException) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 22 with JeesuiteBaseException

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

the class SHA1 method getSHA1.

/**
 * <p>
 * 用SHA1算法生成安全签名
 * </p>
 *
 * @param token
 * 				票据
 * @param timestamp
 * 				时间戳
 * @param nonce
 * 				随机字符串
 * @param encrypt
 * 				密文
 * @return 安全签名
 *
 * @throws AESException {@link AESException}
 */
public static String getSHA1(String token, String timestamp, String nonce, String encrypt) {
    try {
        String[] array = new String[] { token, timestamp, nonce, encrypt };
        StringBuffer sb = new StringBuffer();
        /* 字符串排序 */
        Arrays.sort(array);
        for (int i = 0; i < 4; i++) {
            sb.append(array[i]);
        }
        /* SHA1签名生成 */
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(sb.toString().getBytes());
        byte[] digest = md.digest();
        StringBuffer hexstr = new StringBuffer();
        String shaHex = "";
        for (int i = 0; i < digest.length; i++) {
            shaHex = Integer.toHexString(digest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexstr.append(0);
            }
            hexstr.append(shaHex);
        }
        return hexstr.toString();
    } catch (Exception e) {
        throw new JeesuiteBaseException(500, "error", e);
    }
}
Also used : JeesuiteBaseException(com.mendmix.common.JeesuiteBaseException) MessageDigest(java.security.MessageDigest) JeesuiteBaseException(com.mendmix.common.JeesuiteBaseException)

Example 23 with JeesuiteBaseException

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

the class HttpResponseEntity method getUnwrapBody.

public String getUnwrapBody() {
    jsonBody = body != null && JsonUtils.isJsonString(body);
    if (jsonBody) {
        JsonNode jsonNode = JsonUtils.getNode(body, null);
        // 
        if (!jsonNode.has(GlobalConstants.PARAM_CODE)) {
            return body;
        }
        // 
        if (jsonNode.size() > 1 && !jsonNode.has(GlobalConstants.PARAM_DATA) && !jsonNode.has(GlobalConstants.PARAM_MSG) && !jsonNode.has(msgAlias)) {
            return body;
        }
        String code = jsonNode.get(GlobalConstants.PARAM_CODE).asText();
        if (successCodes.contains(code)) {
            JsonNode dataNode = jsonNode.get(GlobalConstants.PARAM_DATA);
            if (dataNode instanceof NullNode) {
                return null;
            }
            return Objects.toString(dataNode, null);
        }
        String bizCode = jsonNode.has("bizCode") ? jsonNode.get("bizCode").textValue() : null;
        String msg = null;
        if (jsonNode.has(GlobalConstants.PARAM_MSG)) {
            msg = jsonNode.get(GlobalConstants.PARAM_MSG).textValue();
        } else {
            msg = jsonNode.get(msgAlias).textValue();
        }
        int statusCode = StringUtils.isNumeric(code) ? Integer.parseInt(code) : 500;
        throw new JeesuiteBaseException(statusCode, bizCode, msg);
    }
    if (!isSuccessed()) {
        throw new JeesuiteBaseException(statusCode, StringUtils.defaultIfBlank(message, "http请求异常"));
    }
    return body;
}
Also used : JeesuiteBaseException(com.mendmix.common.JeesuiteBaseException) JsonNode(com.fasterxml.jackson.databind.JsonNode) NullNode(com.fasterxml.jackson.databind.node.NullNode)

Example 24 with JeesuiteBaseException

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

the class SqlRewriteHandler method rewriteSql.

/**
 * @param invocation
 * @param dataMappings
 * @return
 */
private void rewriteSql(InvocationVals invocation, Map<String, String[]> dataMapping) {
    String orignSql = invocation.getSql();
    PageParams pageParam = invocation.getPageParam();
    boolean sharddingTenant = false;
    if (isFieldSharddingTenant && !CurrentRuntimeContext.getIgnoreTenant()) {
        sharddingTenant = true;
    }
    boolean softDelete = softDeleteMappedStatements.contains(invocation.getMapperNameSpace()) || softDeleteMappedStatements.contains(invocation.getMappedStatement().getId());
    if (softDelete) {
        if (dataMapping == null)
            dataMapping = new HashMap<>(1);
        dataMapping.put(softDeletePropName, new String[] { softDeleteFalseValue });
    }
    if (deptPropName != null && dataMapping != null && dataMapping.containsKey(orgBasePermKey)) {
        if (deptMappedStatements.contains(invocation.getMapperNameSpace()) || deptMappedStatements.contains(invocation.getMappedStatement().getId())) {
            String departmentId = CurrentRuntimeContext.getAndValidateCurrentUser().getDeptId();
            if (StringUtils.isBlank(departmentId)) {
                throw new JeesuiteBaseException("当前登录用户部门ID为空");
            }
            String[] values = dataMapping.get(orgBasePermKey);
            if (values != null && values.length > 0) {
                if (MatchPolicy.exact.name().equals(values[0])) {
                    dataMapping.put(deptPropName, new String[] { departmentId + QUERY_FUZZY_CHAR });
                } else {
                    dataMapping.put(deptPropName, new String[] { departmentId });
                }
            } else {
                dataMapping.put(deptPropName, new String[] { departmentId });
            }
        }
    }
    if (!softDelete && dataMapping == null && !sharddingTenant) {
        if (pageParam == null || (pageParam.getOrderBys() == null || pageParam.getOrderBys().isEmpty())) {
            return;
        }
    }
    SelectBody selectBody = null;
    try {
        Statement stmt = CCJSqlParserUtil.parse(orignSql);
        selectBody = ((Select) stmt).getSelectBody();
    } catch (JSQLParserException e) {
        logger.error("PARSER_ERROR[" + orignSql + "]", e);
        throw new RuntimeException("sql解析错误");
    }
    handleSelectRewrite(selectBody, invocation, dataMapping, sharddingTenant);
    // 
    invocation.setRewriteSql(selectBody.toString());
}
Also used : JeesuiteBaseException(com.mendmix.common.JeesuiteBaseException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) MappedStatement(org.apache.ibatis.mapping.MappedStatement) Statement(net.sf.jsqlparser.statement.Statement) JSQLParserException(net.sf.jsqlparser.JSQLParserException) PageParams(com.mendmix.common.model.PageParams) SelectBody(net.sf.jsqlparser.statement.select.SelectBody)

Example 25 with JeesuiteBaseException

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

the class SqlRewriteHandler method handleTableDataPermission.

private Expression handleTableDataPermission(Expression originWhere, Table table, Map<String, String[]> dataMapping, boolean sharddingTenant) {
    if (!dataPermMappings.containsKey(table.getName())) {
        return originWhere;
    }
    Set<String> fieldNames;
    Expression newExpression = originWhere;
    String column;
    String[] values;
    Map<String, String> columnMapping = dataPermMappings.get(table.getName());
    fieldNames = columnMapping.keySet();
    boolean withSoftDelete = false;
    boolean withPermiCondition = false;
    for (String fieldName : fieldNames) {
        if (fieldName.equals(softDeletePropName)) {
            withSoftDelete = true;
            continue;
        }
        if (sharddingTenant && fieldName.equals(tenantPropName)) {
            column = tenantColumnName;
            String currentTenantId = CurrentRuntimeContext.getTenantId();
            if (currentTenantId == null)
                throw new JeesuiteBaseException("无法获取当前租户ID");
            values = new String[] { currentTenantId };
        } else {
            if (dataMapping == null || !dataMapping.containsKey(fieldName))
                continue;
            column = columnMapping.get(fieldName);
            values = dataMapping.get(fieldName);
            // 
            if (!withPermiCondition)
                withPermiCondition = true;
        }
        // 如果某个匹配字段为空直接返回null,不在查询数据库
        if (values == null || values.length == 0) {
            EqualsTo equalsTo = new EqualsTo();
            equalsTo.setLeftExpression(new Column(table, column));
            equalsTo.setRightExpression(new StringValue("_PERMISSION_NOT_MATCH_"));
            return equalsTo;
        }
        newExpression = handleColumnDataPermCondition(table, newExpression, column, values);
    }
    // 当前创建人
    if (withPermiCondition && ownerColumnName != null) {
        AuthUser currentUser = CurrentRuntimeContext.getCurrentUser();
        if (currentUser != null) {
            EqualsTo equalsTo = new EqualsTo();
            equalsTo.setLeftExpression(new Column(table, ownerColumnName));
            // TODO 需要按ID匹配否则出现同名
            equalsTo.setRightExpression(new StringValue(currentUser.getName()));
            // 
            newExpression = newExpression == null ? equalsTo : new OrExpression(new Parenthesis(newExpression), equalsTo);
        }
    }
    // 软删除
    if (withSoftDelete) {
        EqualsTo equalsTo = new EqualsTo();
        equalsTo.setLeftExpression(new Column(table, softDeleteColumnName));
        equalsTo.setRightExpression(new StringValue(softDeleteFalseValue));
        newExpression = newExpression == null ? equalsTo : new AndExpression(new Parenthesis(newExpression), equalsTo);
    }
    return newExpression;
}
Also used : AuthUser(com.mendmix.common.model.AuthUser) OrExpression(net.sf.jsqlparser.expression.operators.conditional.OrExpression) Parenthesis(net.sf.jsqlparser.expression.Parenthesis) AndExpression(net.sf.jsqlparser.expression.operators.conditional.AndExpression) JeesuiteBaseException(com.mendmix.common.JeesuiteBaseException) Expression(net.sf.jsqlparser.expression.Expression) OrExpression(net.sf.jsqlparser.expression.operators.conditional.OrExpression) BinaryExpression(net.sf.jsqlparser.expression.BinaryExpression) LikeExpression(net.sf.jsqlparser.expression.operators.relational.LikeExpression) InExpression(net.sf.jsqlparser.expression.operators.relational.InExpression) AndExpression(net.sf.jsqlparser.expression.operators.conditional.AndExpression) Column(net.sf.jsqlparser.schema.Column) EqualsTo(net.sf.jsqlparser.expression.operators.relational.EqualsTo) StringValue(net.sf.jsqlparser.expression.StringValue)

Aggregations

JeesuiteBaseException (com.mendmix.common.JeesuiteBaseException)44 IOException (java.io.IOException)13 CObjectMetadata (com.mendmix.cos.CObjectMetadata)4 CUploadResult (com.mendmix.cos.CUploadResult)4 CosServiceException (com.qcloud.cos.exception.CosServiceException)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 InputStream (java.io.InputStream)4 HashMap (java.util.HashMap)4 Request (okhttp3.Request)4 ApiInfo (com.mendmix.common.model.ApiInfo)2 WrapperResponse (com.mendmix.common.model.WrapperResponse)2 BizSystemModule (com.mendmix.gateway.model.BizSystemModule)2 COSObject (com.qcloud.cos.model.COSObject)2 QiniuException (com.qiniu.common.QiniuException)2 InputStreamReader (java.io.InputStreamReader)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 InvalidKeyException (java.security.InvalidKeyException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 SignatureException (java.security.SignatureException)2 Map (java.util.Map)2