com.jfinal.aop.Invocation Java Examples

The following examples show how to use com.jfinal.aop.Invocation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SessionInViewInterceptor.java    From my_curd with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
public void intercept(Invocation inv) {
    inv.invoke();

    Controller c = inv.getController();
    if (c.getRender() instanceof com.jfinal.render.JsonRender) {
        return;
    }
    HttpSession hs = c.getSession(false);
    if (hs != null) {
        Map session = new com.jfinal.ext.interceptor.SessionInViewInterceptor.JFinalSession(hs);
        for (String sessionField : sessionFields) {
            session.put(sessionField, hs.getAttribute(sessionField));
        }
        c.setAttr("session", session);
    }
}
 
Example #2
Source File: LimiterInterceptor.java    From jboot with Apache License 2.0 6 votes vote down vote up
private void doInterceptForConcurrency(int rate, String resource, String fallback, Invocation inv) {
    Semaphore semaphore = LimiterManager.me().getOrCreateSemaphore(resource, rate);
    boolean acquire = false;
    try {
        acquire = semaphore.tryAcquire();
        if (acquire) {
            inv.invoke();
        }
        //不允许通行
        else {
            doExecFallback(resource, fallback, inv);
        }
    } finally {
        if (acquire) {
            semaphore.release();
        }
    }
}
 
Example #3
Source File: LimiterInterceptor.java    From jboot with Apache License 2.0 6 votes vote down vote up
@Override
public void intercept(Invocation inv) {
    String packageOrTarget = getPackageOrTarget(inv);
    LimiterManager.TypeAndRate typeAndRate = LimiterManager.me().matchConfig(packageOrTarget);

    if (typeAndRate != null) {
        doInterceptByTypeAndRate(typeAndRate, packageOrTarget, inv);
        return;
    }

    EnableLimit enableLimit = inv.getMethod().getAnnotation(EnableLimit.class);
    if (enableLimit != null) {
        String resource = StrUtil.obtainDefaultIfBlank(enableLimit.resource(), packageOrTarget);
        doInterceptByLimitInfo(enableLimit, resource, inv);
        return;
    }

    inv.invoke();
}
 
Example #4
Source File: BusinessExceptionInterceptor.java    From jboot-admin with Apache License 2.0 6 votes vote down vote up
@Override
public void intercept(Invocation inv) {
	try {
		inv.invoke();
	} catch (JbootException e) {
		if (inv.getTarget() instanceof JbootController) {
			JbootController controller = inv.getTarget();

			if (controller.isAjaxRequest()) {
				RestResult<String> restResult = new RestResult<String>();
				restResult.error(e.getMessage());
				controller.renderJson(restResult);
			} else {
				controller.setAttr(MESSAGE_TAG, e.getMessage()).render(exceptionView);
			}
		}
	}
}
 
Example #5
Source File: NotNullParaInterceptor.java    From jboot-admin with Apache License 2.0 6 votes vote down vote up
private void renderError(Invocation inv, String param, String errorRedirect) {
    if (StrUtils.isNotBlank(errorRedirect)) {
        inv.getController().redirect(errorRedirect);
        return;
    }

    Controller controller = inv.getController();
    if (controller instanceof JbootController) {
        JbootController jc = (JbootController) controller;
        if (jc.isAjaxRequest()) {
            jc.renderJson(RestResult.buildError("参数["+param+"]不可为空"));
            return;
        }
    }
    controller.setAttr(BusinessExceptionInterceptor.MESSAGE_TAG, "参数["+param+"]不可为空").render(exceptionView);
}
 
Example #6
Source File: JbootCacheInterceptor.java    From jboot with Apache License 2.0 6 votes vote down vote up
private <M extends JbootModel> Object getCopyObject(Invocation inv, Object data) {
    if (data instanceof List) {
        return ModelCopier.copy((List<? extends JbootModel>) data);
    } else if (data instanceof Set) {
        return ModelCopier.copy((Set<? extends JbootModel>) data);
    } else if (data instanceof Page) {
        return ModelCopier.copy((Page<? extends JbootModel>) data);
    } else if (data instanceof JbootModel) {
        return ModelCopier.copy((JbootModel) data);
    } else if (data.getClass().isArray()
            && JbootModel.class.isAssignableFrom(data.getClass().getComponentType())) {
        return ModelCopier.copy((M[]) data);
    } else {
        throw newException(null, inv, data);
    }
}
 
Example #7
Source File: BlackListInterceptor.java    From zrlog with Apache License 2.0 6 votes vote down vote up
@Override
public void intercept(Invocation invocation) {
    if (invocation.getController() instanceof BaseController) {
        BaseController baseController = (BaseController) invocation.getController();
        String ipStr = (String) Constants.WEB_SITE.get("blackList");
        if (ipStr != null) {
            Set<String> ipSet = new HashSet<>(Arrays.asList(ipStr.split(",")));
            String requestIP = WebTools.getRealIp(baseController.getRequest());
            if (ipSet.contains(requestIP)) {
                baseController.render(JFinal.me().getConstants().getErrorView(403));
            } else {
                invocation.invoke();
            }
        } else {
            invocation.invoke();
        }
    } else {
        invocation.invoke();
    }
}
 
Example #8
Source File: CORSInterceptor.java    From jboot with Apache License 2.0 6 votes vote down vote up
@Override
public void intercept(Invocation inv) {

    EnableCORS enableCORS = getAnnotation(inv);

    if (enableCORS == null) {
        inv.invoke();
        return;
    }


    doConfigCORS(inv, enableCORS);


    String method = inv.getController().getRequest().getMethod();
    if (METHOD_OPTIONS.equals(method)) {
        inv.getController().renderText("");
    } else {
        inv.invoke();
    }
}
 
Example #9
Source File: ParaValidateInterceptor.java    From jboot with Apache License 2.0 6 votes vote down vote up
/**
 * 对验证码进行验证
 *
 * @param inv
 * @param captchaValidate
 * @return
 */
private boolean validateCaptache(Invocation inv, CaptchaValidate captchaValidate) {
    String formName = AnnotationUtil.get(captchaValidate.form());
    if (StrUtil.isBlank(formName)) {
        throw new IllegalArgumentException("@CaptchaValidate.form must not be empty in " + inv.getController().getClass().getName() + "." + inv.getMethodName());
    }


    Controller controller = inv.getController();
    if (controller.validateCaptcha(formName)) {
        return true;
    }

    renderError(inv.getController()
            , AnnotationUtil.get(captchaValidate.renderType())
            , formName
            , AnnotationUtil.get(captchaValidate.message())
            , AnnotationUtil.get(captchaValidate.redirectUrl())
            , AnnotationUtil.get(captchaValidate.htmlPath())
            , captchaValidate.errorCode()
    );

    return false;
}
 
Example #10
Source File: WechatInterceptor.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void intercept(Invocation inv) {
    if (enable == false) {
        inv.invoke();
        return;
    }


    String uid = CookieUtil.get(inv.getController(), JPressConsts.COOKIE_UID);
    if (StrUtil.isNotBlank(uid)) {
        inv.invoke();
        return;
    }

    if (RequestUtil.isWechatBrowser(inv.getController().getRequest()) == false) {
        inv.invoke();
        return;
    }

    String gotoUrl = getGotoUrl(inv.getController());
    inv.getController().redirect("/wechat/authorization?goto=" + gotoUrl);
}
 
Example #11
Source File: JbootCachePutInterceptor.java    From jboot with Apache License 2.0 6 votes vote down vote up
@Override
public void intercept(Invocation inv) {

    //先执行,之后再保存数据
    inv.invoke();

    Method method = inv.getMethod();
    CachePut cachePut = method.getAnnotation(CachePut.class);
    if (cachePut == null) {
        return;
    }

    Object data = inv.getReturnValue();

    String unless = AnnotationUtil.get(cachePut.unless());
    if (Utils.isUnless(unless, method, inv.getArgs())) {
        return;
    }

    Class targetClass = inv.getTarget().getClass();
    String cacheName = AnnotationUtil.get(cachePut.name());
    Utils.ensureCachenameAvailable(method, targetClass, cacheName);
    String cacheKey = Utils.buildCacheKey(AnnotationUtil.get(cachePut.key()), targetClass, method, inv.getArgs());

    Utils.putDataToCache(cachePut.liveSeconds(),cacheName,cacheKey,data);
}
 
Example #12
Source File: PermissionInterceptor.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void intercept(Invocation inv) {

    User user = UserInterceptor.getThreadLocalUser();
    if (user == null) {
        render(inv);
        return;
    }

    if (!permissionService.hasPermission(user.getId(), inv.getActionKey())) {
        render(inv);
        return;
    }

    inv.invoke();
}
 
Example #13
Source File: AbstractSentinelProccesser.java    From jboot with Apache License 2.0 6 votes vote down vote up
protected Object handleDefaultFallback(Invocation inv, String defaultFallback,
                                       Class<?>[] fallbackClass, Throwable ex) throws Throwable {
    // Execute the default fallback function if configured.
    Method fallbackMethod = extractDefaultFallbackMethod(inv, defaultFallback, fallbackClass);
    if (fallbackMethod != null) {
        // Construct args.
        Object[] args = fallbackMethod.getParameterTypes().length == 0 ? new Object[0] : new Object[]{ex};
        try {
            if (isStatic(fallbackMethod)) {
                return fallbackMethod.invoke(null, args);
            }
            return fallbackMethod.invoke(inv.getTarget(), args);
        } catch (InvocationTargetException e) {
            // throw the actual exception
            throw e.getTargetException();
        }
    }

    // If no any fallback is present, then directly throw the exception.
    throw ex;
}
 
Example #14
Source File: AbstractSentinelProccesser.java    From jboot with Apache License 2.0 6 votes vote down vote up
protected Object handleBlockException(Invocation inv, SentinelResource annotation, BlockException ex)
        throws Throwable {

    // Execute block handler if configured.
    Method blockHandlerMethod = extractBlockHandlerMethod(inv, annotation.blockHandler(),
            annotation.blockHandlerClass());
    if (blockHandlerMethod != null) {
        Object[] originArgs = inv.getArgs();
        // Construct args.
        Object[] args = Arrays.copyOf(originArgs, originArgs.length + 1);
        args[args.length - 1] = ex;
        try {
            if (isStatic(blockHandlerMethod)) {
                return blockHandlerMethod.invoke(null, args);
            }
            return blockHandlerMethod.invoke(inv.getTarget(), args);
        } catch (InvocationTargetException e) {
            // throw the actual exception
            throw e.getTargetException();
        }
    }

    // If no block handler is present, then go to fallback.
    return handleFallback(inv, annotation, ex);
}
 
Example #15
Source File: AbstractSentinelProccesser.java    From jboot with Apache License 2.0 6 votes vote down vote up
private Method extractFallbackMethod(Invocation inv, String fallbackName, Class<?>[] locationClass) {
    if (StringUtil.isBlank(fallbackName)) {
        return null;
    }
    boolean mustStatic = locationClass != null && locationClass.length >= 1;
    Class<?> clazz = mustStatic ? locationClass[0] : inv.getTarget().getClass();
    MethodWrapper m = ResourceMetadataRegistry.lookupFallback(clazz, fallbackName);
    if (m == null) {
        // First time, resolve the fallback.
        Method method = resolveFallbackInternal(inv, fallbackName, clazz, mustStatic);
        // Cache the method instance.
        ResourceMetadataRegistry.updateFallbackFor(clazz, fallbackName, method);
        return method;
    }
    if (!m.isPresent()) {
        return null;
    }
    return m.getMethod();
}
 
Example #16
Source File: WechatUserInterceptor.java    From jboot with Apache License 2.0 6 votes vote down vote up
@Override
public void intercept(Invocation inv) {

    JbootWechatController controller = (JbootWechatController) inv.getController();

    /**
     * 是否允许访问,默认情况下只有是微信浏览器允许访问
     */
    if (controller.isAllowVisit()) {
        doIntercept(inv);
        return;
    }

    controller.doNotAlloVisitRedirect();

}
 
Example #17
Source File: AbstractSentinelProccesser.java    From jboot with Apache License 2.0 6 votes vote down vote up
private Method extractBlockHandlerMethod(Invocation inv, String name, Class<?>[] locationClass) {
    if (StringUtil.isBlank(name)) {
        return null;
    }

    boolean mustStatic = locationClass != null && locationClass.length >= 1;
    Class<?> clazz;
    if (mustStatic) {
        clazz = locationClass[0];
    } else {
        // By default current class.
        clazz = inv.getTarget().getClass();
    }
    MethodWrapper m = ResourceMetadataRegistry.lookupBlockHandler(clazz, name);
    if (m == null) {
        // First time, resolve the block handler.
        Method method = resolveBlockHandlerInternal(inv, name, clazz, mustStatic);
        // Cache the method instance.
        ResourceMetadataRegistry.updateBlockHandlerFor(clazz, name, method);
        return method;
    }
    if (!m.isPresent()) {
        return null;
    }
    return m.getMethod();
}
 
Example #18
Source File: LimitFallbackProcesserDefault.java    From jboot with Apache License 2.0 6 votes vote down vote up
/**
 * 处理 Controller 的限流
 *
 * @param resource
 * @param inv
 */
protected void doProcessWebLimit(String resource, Invocation inv) {

    Controller controller = inv.getController();
    controller.getResponse().setStatus(config.getDefaultHttpCode());

    if (RequestUtil.isAjaxRequest(controller.getRequest())) {
        controller.renderJson(config.getDefaultAjaxContent());
    }
    //非ajax的正常请求
    else {
        String limitView = config.getDefaultHtmlView();
        if (limitView != null) {
            controller.render(limitView);
        } else {
            controller.renderText("reqeust limit.");
        }
    }
}
 
Example #19
Source File: ComActionInterceptor.java    From my_curd with Apache License 2.0 6 votes vote down vote up
@Override
public void intercept(Invocation inv) {
    inv.getController().setAttr("setting", Constant.SETTING);

    String errMsg = null;
    try {
        inv.invoke();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        errMsg = ExceptionUtils.getMessage(e);
    }

    // 返回异常信息
    if (StringUtils.notEmpty(errMsg)) {
        String requestType = inv.getController().getRequest().getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(requestType) || StringUtils.notEmpty(inv.getController().getPara("xmlHttpRequest"))) {
            Ret ret = Ret.create().set("state", "error").set("msg", errMsg);
            inv.getController().render(new JsonRender(ret).forIE());
        } else {
            inv.getController().setAttr("errorMsg", errMsg);
            inv.getController().render(Constant.VIEW_PATH + "/common/500.ftl");
        }
    }
}
 
Example #20
Source File: VisitLogInterceptor.java    From my_curd with Apache License 2.0 6 votes vote down vote up
@Override
    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        SysVisitLog sysVisitLog = new SysVisitLog();
        sysVisitLog.setId(IdUtils.id());
        sysVisitLog.setSysUserIp(WebUtils.getRemoteAddress(controller.getRequest()));
        sysVisitLog.setSysUser(WebUtils.getSessionUsername(controller));
        sysVisitLog.setUrl(inv.getActionKey());
        sysVisitLog.setRequestType(controller.getRequest().getMethod());
        sysVisitLog.setCreateTime(new Date());

        Map<String, String[]> params = controller.getRequest().getParameterMap();
        if (params.keySet().size() > 0) {
            sysVisitLog.setParam(JSON.toJSONString(params));
//            if (sysVisitLog.getParam().length() > 100) {
//                sysVisitLog.setParam("超长文本参数");
//            }
        }
        sysVisitLog.save();
        inv.invoke();
    }
 
Example #21
Source File: JwtInterceptor.java    From jboot with Apache License 2.0 6 votes vote down vote up
private void refreshIfNecessary(Invocation inv, Map oldData) {
    if (oldData == null) {
        return;
    }

    // Jwt token 的发布时间
    Long isuuedAtMillis = (Long) oldData.get(ISUUED_AT);
    if (isuuedAtMillis == null || JwtManager.me().getConfig().getValidityPeriod() <= 0) {
        return;
    }

    Long nowMillis = System.currentTimeMillis();
    long savedMillis = nowMillis - isuuedAtMillis;

    if (savedMillis > JwtManager.me().getConfig().getValidityPeriod() / 2) {
        String token = JwtManager.me().createJwtToken(oldData);
        HttpServletResponse response = inv.getController().getResponse();
        response.addHeader(JwtManager.me().getHttpHeaderName(), token);
    }

}
 
Example #22
Source File: SeataGlobalTransactionalInterceptor.java    From jboot with Apache License 2.0 6 votes vote down vote up
@Override
public void intercept(Invocation inv) {
    if (!JbootSeataManager.me().isEnable()) {
        inv.invoke();
        return;
    }
    Method method = inv.getMethod();
    final SeataGlobalTransactional globalTrxAnno = method.getAnnotation(SeataGlobalTransactional.class);
    final SeataGlobalLock globalLockAnno = method.getAnnotation(SeataGlobalLock.class);
    try {
        if (globalTrxAnno != null) {
            handleGlobalTransaction(inv, globalTrxAnno);
        } else if (globalLockAnno != null) {
            handleGlobalLock(inv);
        } else {
            inv.invoke();
        }
    } catch (Throwable e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

}
 
Example #23
Source File: JbootShiroInvokeListener.java    From jboot with Apache License 2.0 6 votes vote down vote up
@Override
public void onInvokeAfter(Invocation inv, AuthorizeResult result) {
    if (result.isOk()) {
        inv.invoke();
        return;
    }

    int errorCode = result.getErrorCode();
    switch (errorCode) {
        case AuthorizeResult.ERROR_CODE_UNAUTHENTICATED:
            doProcessUnauthenticated(inv.getController());
            break;
        case AuthorizeResult.ERROR_CODE_UNAUTHORIZATION:
            doProcessuUnauthorization(inv.getController());
            break;
        default:
            inv.getController().renderError(404);
    }
}
 
Example #24
Source File: MyI18nInterceptor.java    From zrlog with Apache License 2.0 5 votes vote down vote up
@Override
public void intercept(Invocation inv) {
    if (Constants.IN_JAR) {
        I18nUtil.addToRequest(null, inv.getController().getRequest(), JFinal.me().getConstants().getDevMode(), false);
    } else {
        I18nUtil.addToRequest(PathKit.getRootClassPath(), inv.getController().getRequest(), JFinal.me().getConstants().getDevMode(), false);
    }
    inv.invoke();
}
 
Example #25
Source File: LimitFallbackProcesserDefault.java    From jboot with Apache License 2.0 5 votes vote down vote up
@Override
public void process(String resource, String fallback, Invocation inv) {

    if (StrUtil.isNotBlank(fallback)) {
        doProcessFallback(fallback, inv);
        return;
    }

    if (inv.isActionInvocation()) {
        doProcessWebLimit(resource, inv);
    } else {
        doProcessServiceLimit(resource, inv);
    }
}
 
Example #26
Source File: AdminInterceptor.java    From zrlog with Apache License 2.0 5 votes vote down vote up
/**
 * 为了规范代码,这里做了一点类是Spring的ResponseEntity的东西,及通过方法的返回值来判断是应该返回页面还会对应JSON数据
 * 具体方式看 AdminRouters,这里用到了 ThreadLocal
 *
 * @param ai
 */
private void adminPermission(Invocation ai) {
    Controller controller = ai.getController();
    AdminTokenVO adminTokenVO = adminTokenService.getAdminTokenVO(controller.getRequest());
    if (adminTokenVO != null) {
        try {
            User user = new User().findById(adminTokenVO.getUserId());
            if (StringUtils.isEmpty(user.getStr("header"))) {
                user.set("header", Constants.DEFAULT_HEADER);
            }
            controller.setAttr("user", user);
            controller.setAttr("protocol", adminTokenVO.getProtocol());
            TemplateHelper.fullTemplateInfo(controller, false);
            if (!"/admin/logout".equals(ai.getActionKey())) {
                adminTokenService.setAdminToken(user, adminTokenVO.getSessionId(), adminTokenVO.getProtocol(), controller.getRequest(), controller.getResponse());
            }
            ai.invoke();
            // 存在消息提示
            if (controller.getAttr("message") != null) {
                initIndex(controller.getRequest());
                controller.render(new FreeMarkerRender("/admin/index.ftl"));
            } else {
                if (!tryDoRender(ai, controller)) {
                    controller.renderHtml(IOUtil.getStringInputStream(new FileInputStream(PathKit.getWebRootPath() + Constants.NOT_FOUND_PAGE)));
                }
            }
        } catch (Exception e) {
            LOGGER.error("", e);
            exceptionHandler(ai, e);
        } finally {
            AdminTokenThreadLocal.remove();
        }
    } else if ("/admin/login".equals(ai.getActionKey()) || "/api/admin/login".equals(ai.getActionKey())) {
        ai.invoke();
        tryDoRender(ai, controller);
    } else {
        blockUnLoginRequestHandler(ai);
    }
}
 
Example #27
Source File: AdminInterceptor.java    From zrlog with Apache License 2.0 5 votes vote down vote up
private void blockUnLoginRequestHandler(Invocation ai) {
    if (ai.getActionKey().startsWith("/api")) {
        ExceptionResponse exceptionResponse = new ExceptionResponse();
        exceptionResponse.setError(1);
        exceptionResponse.setMessage(I18nUtil.getStringFromRes("admin.session.timeout"));
        ai.getController().renderJson(exceptionResponse);
    } else {
        try {
            loginRender(ai.getController());
        } catch (Exception e) {
            LOGGER.error("", e);
        }
    }
}
 
Example #28
Source File: SeataGlobalTransactionalInterceptor.java    From jboot with Apache License 2.0 5 votes vote down vote up
private void handleGlobalLock(final Invocation inv) throws Exception {
    JbootSeataManager.me().getGlobalLockTemplate().execute(() -> {
        try {
            inv.invoke();
            return inv.getReturnValue();
        } catch (Throwable e) {
            if (e instanceof Exception) {
                throw (Exception)e;
            } else {
                throw new RuntimeException(e);
            }
        }
    });
}
 
Example #29
Source File: LimiterInterceptor.java    From jboot with Apache License 2.0 5 votes vote down vote up
private void doInterceptForTokenBucket(int rate, String resource, String fallback, Invocation inv) {
    RateLimiter limiter = LimiterManager.me().getOrCreateRateLimiter(resource, rate);
    //允许通行
    if (limiter.tryAcquire()) {
        inv.invoke();
    }
    //不允许通行
    else {
        doExecFallback(resource, fallback, inv);
    }
}
 
Example #30
Source File: LogInterceptor.java    From jboot-admin with Apache License 2.0 5 votes vote down vote up
@Override
public void intercept(Invocation inv) {
	if (inv.getController() instanceof BaseController) {
		BaseController c = (BaseController) inv.getController();

		User user = AuthUtils.getLoginUser();
		UserAgent userAgent = UserAgent.parseUserAgentString(c.getRequest().getHeader("User-Agent"));
		Browser browser = userAgent.getBrowser();

		Log log = new Log();
		log.setUid(user.getId());
		log.setBrowser(browser.getName());
		log.setOperation(c.getRequest().getMethod());
		log.setFrom(c.getReferer());
		log.setIp(c.getIPAddress());
		log.setUrl(c.getRequest().getRequestURI());
		log.setCreateDate(new Date());
		log.setLastUpdAcct(user.getId() == null ? "guest" : user.getName());
		log.setLastUpdTime(new Date());
		log.setNote("记录日志");

		try {
			LogService logService = Jboot.service(LogService.class);
			logService.save(log);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		} finally {
			inv.invoke();
		}
	} else {
		inv.invoke();
	}
}