org.nutz.mvc.Mvcs Java Examples

The following examples show how to use org.nutz.mvc.Mvcs. 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: Globals.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
 * 获取上传文件的根目录
 *
 * @return
 */
public static String getUserfilesBaseDir() {
    String dir = getConfig("userfiles.basedir");
    if (Strings.isBlank(dir)) {
        try {
            dir = Mvcs.getServletContext().getRealPath("/");
        } catch (Exception e) {
            return "";
        }
    }
    if (!dir.endsWith("/")) {
        dir += "/";
    }
    // System.out.println("userfiles.basedir: " + dir);
    return dir;
}
 
Example #2
Source File: AsyncFactory.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
     * 同步session到数据库
     *
     * @param session 在线用户会话
     * @return 任务task
     */
    public TimerTask syncSessionToDb(OnlineSession session) {
        return new TimerTask() {
            @Override
            public void run() {
                UserOnline online = new UserOnline();
                online.setSessionId(String.valueOf(session.getId()));
                online.setDeptName(session.getDeptName());
                online.setLoginName(session.getLoginName());
                online.setStartTimestamp(session.getStartTimestamp());
                online.setLastAccessTime(session.getLastAccessTime());
                online.setExpireTime(session.getTimeout());
                online.setIpaddr(Lang.getIP(Mvcs.getReq()));
                online.setLoginLocation(AddressUtils.getRealAddressByIP(Lang.getIP(Mvcs.getReq())));
                online.setBrowser(session.getBrowser());
                online.setOs(session.getOs());
//                online.setStatus(session.getStatus());
                online.setSession(session);
                userOnlineService.insert(online);

            }
        };
    }
 
Example #3
Source File: JWTUtil.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
 *  获取ID
 * @return
 */
public static String getId() {
    HttpServletRequest request = Mvcs.getReq();
    Map<String, String> map = new HashMap<String, String>();
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        map.put(key, value);
    }
    try{
        String token=map.get("authorization");
       if(verifyToken(token)){
           Claims claims = Jwts.parser()
                   .setSigningKey(key)
                   .parseClaimsJws(token).getBody();
           return  claims.getId();
       }
    }catch (Exception e){
        log.debug(e.getMessage());
        e.printStackTrace();

    }
    return null;
}
 
Example #4
Source File: GlobalsSettingProcessor.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
@Override
    public void process(ActionContext ac) throws Throwable {

        boolean captcha = Boolean.valueOf(Globals.getConfig("login.captcha"));
        String path = ac.getServletContext().getContextPath();
        String projectName = path.length() > 0 ? path + "/" : "/";
        ac.getRequest().setAttribute("AppBase", projectName);
        ac.getRequest().setAttribute("captchaEnabled", captcha);
        ac.getRequest().setAttribute("pubkey", Globals.getPublicKey());
//      //允许跨越
//        ac.getResponse().addHeader("Access-Control-Allow-Origin", "*");
//        ac.getResponse().addHeader("Access-Control-Allow-Credentials", "true");
//        ac.getResponse().addHeader("Access-Control-Allow-Headers",
//                "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie");
        // 如果url中有语言属性则设置
        String lang = ac.getRequest().getParameter("lang");
        if (!Strings.isEmpty(lang)) {
            Mvcs.setLocalizationKey(lang);
        } else {
            // Mvcs.getLocalizationKey()  1.r.56 版本是null,所以要做两次判断, 1.r.57已修复为默认值 Nutz:Fix issue 1072
            lang = Strings.isBlank(Mvcs.getLocalizationKey()) ? Mvcs.getDefaultLocalizationKey() : Mvcs.getLocalizationKey();
        }
        ac.getRequest().setAttribute("lang", lang);
        doNext(ac);
    }
 
Example #5
Source File: AccessTokenAopInterceptor.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
 * 过滤器 验证登录
 * @param chain
 * @throws Throwable
 */
@Override
public void filter(InterceptorChain chain) throws Throwable {
    try {
        String token = Strings.sNull(Mvcs.getReq().getHeader("authorization"));
        if (JWTUtil.verifyToken(token)) {
            chain.doChain();
        }else {
            Mvcs.SKIP_COMMITTED =true;
            Mvcs.write(Mvcs.getResp(), Result.token(), JsonFormat.full());
        }
    } catch (Throwable e) {
        log.debug("aop.error", e);
        throw e;
    }
}
 
Example #6
Source File: CacheSessionDAO.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
@Override
  protected void doUpdate(Session session) {
  	if (session == null || session.getId() == null) {  
          return;
      }
  	
  	HttpServletRequest request = Mvcs.getReq();
if (request != null){
	String uri = Mvcs.getReq().getRequestURI();
	// 如果是静态文件,则不更新SESSION
	if (isStaticFile(uri)){
		return;
	}

}
  	super.doUpdate(session);
  	logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : "");
  }
 
Example #7
Source File: SessionCacheManager.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public V get(K key) throws CacheException {
    if (key == null){
        return null;
    }

    V v = null;
    HttpServletRequest request =  Mvcs.getReq();
    if (request != null){
        v = (V)request.getAttribute(cacheKeyName);
        if (v != null){
            return v;
        }
    }

    V value = null;
    value = (V)getSession().getAttribute(cacheKeyName);
    logger.debug("get {} {} {}", cacheKeyName, key, request != null ? request.getRequestURI() : "");

    if (request != null && value != null){
        request.setAttribute(cacheKeyName, value);
    }
    return value;
}
 
Example #8
Source File: CacheSessionDAO.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
@Override
  protected Serializable doCreate(Session session) {
HttpServletRequest request = Mvcs.getReq();
if (request != null){
	String uri = Mvcs.getReq().getRequestURI();
	// 如果是静态文件,则不创建SESSION
	if (isStaticFile(uri)){
        return null;
	}
}
super.doCreate(session);
logger.debug("doCreate {} {}", session, request != null ? request.getRequestURI() : "");
  	return session.getId();
  }
 
Example #9
Source File: BeetlViewMaker.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public BeetlViewMaker() throws IOException {
    // 主动设置webroot, 解决maven项目下,Beetl无法找到正确的webapp路径的问题
		String webroot = null;
		if(Mvcs.getServletContext()!=null){
			webroot = Mvcs.getServletContext().getRealPath("/");
	        if (!Strings.isBlank(webroot))
	            BeetlUtil.setWebroot(webroot);
    }
		 
    init();
}
 
Example #10
Source File: BeetlView.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Throwable {
    String child = evalPath(req, obj);
    if (child == null) {
        child = Mvcs.getActionContext().getPath();
    }
    if (obj != null && req.getAttribute("obj") == null)
        req.setAttribute("obj", obj);
    if (resp.getContentType() == null)
    	resp.setContentType("text/html");
    render.render(child, req, new LazyResponseWrapper(resp));
}
 
Example #11
Source File: ActionMethodInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    Object ret) throws Throwable {
    HttpServletResponse response = Mvcs.getResp();

    AbstractSpan span = ContextManager.activeSpan();
    if (response.getStatus() >= 400) {
        span.errorOccurred();
        Tags.STATUS_CODE.set(span, Integer.toString(response.getStatus()));
    }
    ContextManager.stopSpan();
    return ret;
}
 
Example #12
Source File: ActionMethodInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    MethodInterceptResult result) throws Throwable {
    PathMappingCache pathMappingCache = (PathMappingCache) objInst.getSkyWalkingDynamicField();
    String requestURL = pathMappingCache.findPathMapping(method);
    if (requestURL == null) {
        At methodRequestMapping = method.getAnnotation(At.class);
        if (methodRequestMapping.value().length > 0) {
            requestURL = methodRequestMapping.value()[0];
        } else {
            requestURL = "";
        }
        pathMappingCache.addPathMapping(method, requestURL);
        requestURL = pathMappingCache.findPathMapping(method);
    }

    HttpServletRequest request = Mvcs.getReq();
    ContextCarrier contextCarrier = new ContextCarrier();
    CarrierItem next = contextCarrier.items();
    while (next.hasNext()) {
        next = next.next();
        next.setHeadValue(request.getHeader(next.getHeadKey()));
    }
    AbstractSpan span = ContextManager.createEntrySpan(requestURL, contextCarrier);
    Tags.URL.set(span, request.getRequestURL().toString());
    Tags.HTTP.METHOD.set(span, request.getMethod());
    span.setComponent(ComponentsDefine.NUTZ_MVC_ANNOTATION);
    SpanLayer.asHttp(span);
}
 
Example #13
Source File: JedisCacheManager.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
      @Aop("redis")
public V get(K key) throws CacheException {
	if (key == null){
		return null;
	}
	
	V v = null;
	HttpServletRequest request = Mvcs.getReq();
	if (request != null){
		v = (V)request.getAttribute(cacheKeyName);
		if (v != null){
			return v;
		}
	}
	
	V value = null;
	Jedis jedis = null;
	try {
		jedis = jedisAgent.getResource();
              value = (V) jedis().hget(JedisUtils.getBytesKey(cacheKeyName),JedisUtils.getBytesKey(cacheKeyName));
		logger.debug("get {} {} {}", cacheKeyName, key, request != null ? request.getRequestURI() : "");
	} catch (Exception e) {
		logger.error("get {} {} {}", cacheKeyName, key, request != null ? request.getRequestURI() : "", e);
	} finally {
		Streams.safeClose(jedis);
	}
	
	if (request != null && value != null){
		request.setAttribute(cacheKeyName, value);
	}
	
	return value;
}
 
Example #14
Source File: SessionCacheManager.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
@Override
public V put(K key, V value) throws CacheException {
    if (key == null){
        return null;
    }

    getSession().setAttribute(cacheKeyName, value);

    if (logger.isDebugEnabled()){
        HttpServletRequest request = Mvcs.getReq();
        logger.debug("put {} {} {}", cacheKeyName, key, request != null ? request.getRequestURI() : "");
    }

    return value;
}
 
Example #15
Source File: JedisSessionDAO.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
@Override
protected Serializable doCreate(Session session) {
    HttpServletRequest request =  Mvcs.getReq();
    if (request != null){
        String uri = request.getServletPath();
        // 如果是静态文件,则不创建SESSION
        if (isStaticFile(uri)){
            return null;
        }
    }
    Serializable sessionId = this.generateSessionId(session);
    this.assignSessionId(session, sessionId);
    this.update(session);
    return sessionId;
}
 
Example #16
Source File: ErrorProcessor.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
@Override
public void process(ActionContext ac) throws Throwable {
    if (log.isWarnEnabled()) {
        String uri = Mvcs.getRequestPath(ac.getRequest());
        log.warn(String.format("Error@%s :", uri), ac.getError());
    }
    String msg = "system.paramserror";
    if (ac.getError() instanceof ErrorException) {
        msg = ac.getError().getMessage();
    }
    if (ac.getError() instanceof RuntimeException ){
        Throwable error = Lang.unwrapThrow(ac.getError());
        if(error instanceof FailToCastObjectException){
            msg = Mvcs.getMessage(ac.getRequest(),"system.object.exception") + error.getMessage();
        }
        if(error instanceof NumberFormatException ){
            msg = Mvcs.getMessage(ac.getRequest(),"system.object.exception") + error.getMessage();
        }
    }
    //非AJAX 处理
    if (isAjax(ac.getRequest())) {
        NutShiro.rendAjaxResp(ac.getRequest(), ac.getResponse(), Result.error(msg));
    }else {
        new HttpStatusView(500).render(
                ac.getRequest(),
                ac.getResponse(),
                Mvcs.getMessage(ac.getRequest(),
                        msg)
        );
    }
    super.process(ac);
}
 
Example #17
Source File: XssSqlFilterProcessor.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
@Override
public void process(ActionContext ac) throws Throwable {
    if (checkParams(ac)) {
        if (NutShiro.isAjax(ac.getRequest())) {
            ac.getResponse().addHeader("loginStatus", "paramsDenied");
            NutShiro.rendAjaxResp(ac.getRequest(), ac.getResponse(), Result.error(Mvcs.getMessage(ac.getRequest(), "system.paramserror")));
        } else {
            new ForwardView(lerrorUri).render(ac.getRequest(), ac.getResponse(), Mvcs.getMessage(ac.getRequest(), "system.paramserror"));
        }
        return;
    }
    doNext(ac);
}
 
Example #18
Source File: SlogService.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
public SlogBean c(String t, String tag, String source, String msg) {
    SlogBean sysLog = new SlogBean();
    sysLog.setCt(new Date());
    if (t == null || tag == null || msg == null) {
        throw new RuntimeException("t/tag/msg can't null");
    }
    if (source == null) {
        StackTraceElement[] tmp = Thread.currentThread().getStackTrace();
        if (tmp.length > 3) {
            source = tmp[3].getClassName() + "#" + tmp[3].getMethodName();
        } else {
            source = "main";
        }
    }
    sysLog.setT(t);;
    sysLog.setTag(tag);;
    sysLog.setSource(source);;
    sysLog.setMsg(msg);;
    if (Mvcs.getReq() != null) {
        sysLog.setUrl(Mvcs.getReq().getRequestURI());
        sysLog.setIp(Lang.getIP(Mvcs.getReq()));
        //获取地址
        sysLog.setLocation(AddressUtils.getRealAddressByIP(sysLog.getIp()));
        Map<String, String[]> map = Mvcs.getReq().getParameterMap();
        String params = JSONObject.toJSONString(map);
        //设置参数值
        sysLog.setParam(StringUtils.substring(params, 0, 255));
        UserAgent userAgent = UserAgent.parseUserAgentString(Mvcs.getReq().getHeader("User-Agent"));
        if(Lang.isNotEmpty(userAgent)){
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            sysLog.setOs(os);
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            sysLog.setBrowser(browser);
        }
    }
    return sysLog;
}
 
Example #19
Source File: JedisSessionDAO.java    From NutzSite with Apache License 2.0 4 votes vote down vote up
@Override
    public void update(Session session) throws UnknownSessionException {
        if (session == null || session.getId() == null) {
            return;
        }

        HttpServletRequest request = Mvcs.getReq();
        if (request != null){
            String uri = request.getServletPath();
            // 如果是静态文件,则不更新SESSION
            if (isStaticFile(uri)){
                return;
            }

            // 手动控制不更新SESSION
//            if (Global.NO.equals(request.getParameter("updateSession"))){
//                return;
//            }
        }

        Jedis jedis = null;
        try {

            jedis = jedisAgent.getResource();

            // 获取登录者编号
            PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            String principalId = pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY;

            jedis.hset(sessionKeyPrefix, session.getId().toString(), principalId + "|" + session.getTimeout() + "|" + session.getLastAccessTime().getTime());
            jedis.set(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()), JedisUtils.toBytes(session));

            // 设置超期时间
            int timeoutSeconds = (int)(session.getTimeout() / 1000);
            jedis.expire((sessionKeyPrefix + session.getId()), timeoutSeconds);

            logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : "");
        } catch (Exception e) {
            logger.error("update {} {}", session.getId(), request != null ? request.getRequestURI() : "", e);
        } finally {
           Streams.safeClose(jedis);
        }
    }
 
Example #20
Source File: AsyncFactory.java    From NutzSite with Apache License 2.0 4 votes vote down vote up
/**
     * 记录登陆信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    public TimerTask recordLogininfor(String username, boolean status, HttpServletRequest req, String message, Object... args) {
        UserAgent userAgent = UserAgent.parseUserAgentString(Mvcs.getReq().getHeader("User-Agent"));
        String ip = Lang.getIP(req);
        sys_user_logger.info("登录IP:" + ip);
        return new TimerTask() {
            @Override
            public void run() {
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(AddressUtils.getRealAddressByIP(ip));
                s.append(LogUtils.getBlock(username));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                // 打印信息到日志
                sys_user_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                Logininfor logininfor = new Logininfor();
                logininfor.setLoginName(username);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                logininfor.setStatus(status);
                logininfor.setLoginTime(new Date());
                // 日志状态
//                if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status))
//                {
//                    logininfor.setStatus(Constants.SUCCESS);
//                }
//                else if (Constants.LOGIN_FAIL.equals(status))
//                {
//                    logininfor.setStatus(Constants.FAIL);
//                }
                // 插入数据
                logininforService.insert(logininfor);
            }
        };
    }
 
Example #21
Source File: Result.java    From NutzSite with Apache License 2.0 4 votes vote down vote up
public Result(int code, String msg, Object data) {
    this.code = code;
    this.msg = Strings.isBlank(msg) ? "" : Mvcs.getMessage(Mvcs.getActionContext().getRequest(), msg);
    this.data = data;
}
 
Example #22
Source File: MvcUpdateStrategy.java    From NutzSite with Apache License 2.0 2 votes vote down vote up
/**
 * 凡是request中携带update=true,都强制更新缓存
 * @param key
 * @return
 */
@Override
public boolean shouldUpdate(String key) {
    return Lang.parseBoolean(Mvcs.getReq().getParameter("update"));
}