Java Code Examples for com.jfinal.aop.Invocation

The following examples show how to use com.jfinal.aop.Invocation. These examples are extracted from open source projects. 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 Project: jboot-admin   Source File: NotNullParaInterceptor.java    License: 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 2
Source Project: jboot-admin   Source File: BusinessExceptionInterceptor.java    License: 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 3
Source Project: zrlog   Source File: BlackListInterceptor.java    License: 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 4
Source Project: jboot   Source File: ParaValidateInterceptor.java    License: 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 5
Source Project: jboot   Source File: CORSInterceptor.java    License: 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 6
Source Project: jboot   Source File: AbstractSentinelProccesser.java    License: 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 7
Source Project: jboot   Source File: AbstractSentinelProccesser.java    License: 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 8
Source Project: jboot   Source File: AbstractSentinelProccesser.java    License: 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 9
Source Project: jboot   Source File: AbstractSentinelProccesser.java    License: 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 10
Source Project: jboot   Source File: JwtInterceptor.java    License: 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 11
Source Project: jboot   Source File: JbootShiroInvokeListener.java    License: 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 12
Source Project: jboot   Source File: SeataGlobalTransactionalInterceptor.java    License: 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 13
Source Project: jboot   Source File: WechatUserInterceptor.java    License: 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 14
Source Project: jboot   Source File: JbootCachePutInterceptor.java    License: 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 15
Source Project: jboot   Source File: JbootCacheInterceptor.java    License: 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 16
Source Project: jboot   Source File: LimiterInterceptor.java    License: 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 17
Source Project: jboot   Source File: LimiterInterceptor.java    License: 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 18
@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 19
@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 20
Source Project: jboot   Source File: LimitFallbackProcesserDefault.java    License: 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 21
Source Project: my_curd   Source File: VisitLogInterceptor.java    License: 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 22
Source Project: my_curd   Source File: ComActionInterceptor.java    License: 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 23
Source Project: my_curd   Source File: SessionInViewInterceptor.java    License: 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 24
Source Project: jboot-admin   Source File: LogInterceptor.java    License: 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();
	}
}
 
Example 25
Source Project: jboot-admin   Source File: AuthInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void intercept(Invocation ai) {
    if (urls == null) {
        init();
    }

    String url = ai.getActionKey();
    boolean flag = SecurityUtils.getSubject() != null && SecurityUtils.getSubject().isPermitted(url);

    if (urls.contains(url) && !flag) {
        ai.getController().renderError(403);
    } else {
        ai.invoke();
    }
}
 
Example 26
Source Project: zrlog   Source File: InitDataInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private void doIntercept(Invocation invocation) {
    //未安装情况下,尝试跳转去安装
    if (!ZrLogConfig.isInstalled() && !invocation.getActionKey().startsWith(INSTALL_ROUTER_PATH)) {
        invocation.getController().redirect(INSTALL_ROUTER_PATH);
        return;
    }
    if (invocation.getController() instanceof BaseController) {
        HttpServletRequest request = invocation.getController().getRequest();
        BaseController baseController = (BaseController) invocation.getController();
        baseController.setAttr("requrl", ZrLogUtil.getFullUrl(request));
        cacheService.refreshInitDataCache(GlobalResourceHandler.CACHE_HTML_PATH, baseController, false);
        lastAccessTime = System.currentTimeMillis();
    }
    invocation.invoke();
}
 
Example 27
Source Project: jfinal-ext3   Source File: ExceptionInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void intercept(Invocation inv) {
	try {
		inv.invoke();
	} catch (Exception e) {
		if (inv.getTarget() instanceof ControllerExt) {
			((ControllerExt)inv.getTarget()).onExceptionError(e);
		}
		LOG.error(e.getLocalizedMessage());
		throw e;
	}
}
 
Example 28
@Override
public void intercept(Invocation inv) {
    if (WxaConfigKit.getWxaConfig() == null) {
        inv.getController().renderJson(Ret.fail("code", 106).set("message", "jpress mini program config error"));
        return;
    }

    inv.invoke();
}
 
Example 29
public void render(Invocation inv) {
    if (RequestUtil.isAjaxRequest(inv.getController().getRequest())) {
        inv.getController().renderJson(Ret.fail().set("message", "您没有权限操作此功能。"));
    } else {
        inv.getController().render(NO_PERMISSION_VIEW);
    }
}
 
Example 30
@Override
public void intercept(Invocation inv) {

    if (Installer.isInstalled()) {
        inv.getController().renderError(404);
        return;
    }

    inv.invoke();
}