@Override
  public String doIntercept(ActionInvocation invocation) throws Exception {
    Object action = invocation.getAction();
    if (!(action instanceof NoParameters)) {
      ActionContext ac = invocation.getInvocationContext();
      final Map<String, Object> parameters = retrieveParameters(ac);

      if (LOG.isDebugEnabled()) {
        LOG.debug("Setting params " + getParameterLogMap(parameters));
      }

      if (parameters != null) {
        Map<String, Object> contextMap = ac.getContextMap();
        try {
          ReflectionContextState.setCreatingNullObjects(contextMap, true);
          ReflectionContextState.setDenyMethodExecution(contextMap, true);
          ReflectionContextState.setReportingConversionErrors(contextMap, true);

          ValueStack stack = ac.getValueStack();
          setParameters(action, stack, parameters);
        } finally {
          ReflectionContextState.setCreatingNullObjects(contextMap, false);
          ReflectionContextState.setDenyMethodExecution(contextMap, false);
          ReflectionContextState.setReportingConversionErrors(contextMap, false);
        }
      }
    }
    return invocation.invoke();
  }
  @SuppressWarnings("unused")
  @Override
  public String intercept(ActionInvocation actionInvocation) throws Exception {
    String methodName = actionInvocation.getProxy().getMethod();
    Method currentMethod = actionInvocation.getAction().getClass().getMethod(methodName, null);
    // 1、判断客户是否登陆

    // 从session获取当前客户信息
    Employee employee =
        (Employee) ServletActionContext.getRequest().getSession().getAttribute("employee");

    if (employee == null) {
      System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
      System.out.println("客户还没登陆或登陆已超时!!!");
      System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
      System.out.println();
      return "index";
    }
    // 2、进行权限控制判断

    // 如果该请求方法是需要进行验证的则需执行以下逻辑
    if (currentMethod.isAnnotationPresent(Auth.class)) {
      // 获取权限校验的注解
      Auth authority = currentMethod.getAnnotation(Auth.class);
      // 获取当前请求的注解的actionName
      String actionName = authority.actionName();
      // 获取当前请求需要的权限
      String privilege = authority.privilege();

      // 可以在此判断当前客户是否拥有对应的权限,如果没有可以跳到指定的无权限提示页面,如果拥有则可以继续往下执行。

      // if(拥有对应的权限){
      //    return actionInvocation.invoke();
      // }else{
      //    return "无权限";
      // }

      System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
      System.out.println(
          "客户"
              + employee.getUserName()
              + "在"
              + new Date()
              + "执行了"
              + actionName
              + "方法,拥有"
              + privilege
              + "权限!!");
      System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
      System.out.println();
      return actionInvocation.invoke();
    }

    // 3、进行非权限控制判断

    System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
    System.out.println("我执行了没有??");
    System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
    return "index";
  }
  @Override
  public String intercept(ActionInvocation actionInvocation) throws Exception {
    Map<String, Object> session = actionInvocation.getInvocationContext().getSession();
    User user = (User) session.get(GlobalNames.USER);

    if (user == null) {
      return Action.LOGIN;
    } else {
      if (rol != null) {
        if (!user.getLevel().toString().equals("GOD")) {
          if (rol.equals("GOD")) {
            return Action.ERROR;
          }
          if (rol.equals("ADMIN") && !(user.getLevel().toString().equals("ADMIN"))) {
            return Action.ERROR;
          }
        }
      }
      Action action = (Action) actionInvocation.getAction();

      if (action instanceof UserAware) {
        ((UserAware) action).setUser(user);
      }
    }

    return actionInvocation.invoke();
  }
 public String intercept(ActionInvocation invocation) throws Exception {
   ActionContext ctx = invocation.getInvocationContext();
   Map session = ctx.getSession();
   Admin admin = (Admin) session.get("teacher");
   if (admin != null && admin.getAid().intValue() <= 2) return invocation.invoke();
   Object action = invocation.getAction();
   if ((action instanceof BenQResultAction)
       || (action instanceof BenQualityAction)
       || (action instanceof BenResultTAction)
       || (action instanceof BenTResultAction)
       || (action instanceof CO2DataAction)
       || (action instanceof CommentAction)
       || (action instanceof DateDataAction)
       || (action instanceof DateTeamAction)
       || (action instanceof DeleteDataAction)
       || (action instanceof EditTeamAction)
       || (action instanceof GasDataAction)
       || (action instanceof LayExname)
       || (action instanceof LayExNameAction)
       || (action instanceof LayTeamAction)
       || (action instanceof SaltResultAction)
       || (action instanceof StyreneResultAction)
       || (action instanceof TeamHaveData)
       || (action instanceof TeamNoData)
       || (action instanceof UpdateTeamAction)
       || (action instanceof LayDataDispacher)
       || (action instanceof LayTeamDispacherAction)
       || (action instanceof DispacherURLData)) {
     return invocation.invoke();
   } else {
     ctx.put("tip", "You Don't Have The Power to Perform this Action.");
     return "error";
   }
 }
  /*
   * (non-Javadoc)
   *
   * @see
   * com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony
   * .xwork2.ActionInvocation)
   */
  public String intercept(ActionInvocation arg0) throws Exception {
    Map session = arg0.getInvocationContext().getSession();
    String currentUserid = String.valueOf((Long) session.get(Constants.LOGIN_USER_ID));
    long currentUserLoginTime = (Long) session.get(Constants.USER_LOGIN_TIME);
    List userSessionList = LoginAction.userSessionMap.get(currentUserid);
    if (null != userSessionList && 1 < userSessionList.size()) {

      boolean sameUserLoginFlag = false;
      for (Object obj : userSessionList) {
        Map userSession = (Map) obj;

        long userLoginTime = 0;
        // 如果session无效,则会抛出异常
        try {
          userLoginTime = (Long) userSession.get(Constants.USER_LOGIN_TIME);
        } catch (Exception e) {
          continue;
        }

        if (currentUserLoginTime < userLoginTime) {
          sameUserLoginFlag = true;
          break;
        }
      }

      if (sameUserLoginFlag) {
        return "sameuserlogin";
      }
    }

    return arg0.invoke();
  }
  /**
   * Override to handle interception
   *
   * @param invocation
   * @return
   * @throws Exception
   */
  public String intercept(ActionInvocation invocation) throws Exception {
    String _logger_method = "intercept";
    if (log.isTraceEnabled()) {
      log.trace("> " + _logger_method);
    }

    String result;
    try {
      String nextPage = checkAccess(invocation);
      if (nextPage == null) {
        Logger invocationLog = null;
        if (log.isDebugEnabled()) {
          invocationLog = Logger.getLogger(invocation.getAction().getClass());
          invocationLog.debug("> " + invocation.getProxy().getMethod());
        }
        result = invocation.invoke();
        if (log.isDebugEnabled()) {
          invocationLog.debug("< " + invocation.getProxy().getMethod());
        }
      } else {
        result = NavConsts.POPUP_TIME_OUT;
      }
    } catch (Exception e) {
      String excID = Long.toString(System.currentTimeMillis());
      BaseAction baseAction = (BaseAction) invocation.getAction();
      baseAction.addFieldError("errorID", "Error ID: " + excID);
      publishException(invocation, new ExceptionHolder(e));

      return NavConsts.POPUP_GLOBAL_ERROR;
    }
    if (log.isTraceEnabled()) {
      log.trace("< " + _logger_method);
    }
    return result;
  }
  private void setToGoingURL(
      HttpServletRequest request, HttpSession session, ActionInvocation invocation) {
    // 如果referer不为空 直接使用它。如果为空我们分别获得命名空间,action名,以及请求参数
    // 从新构造成一个URL保存在session中
    String url = request.getHeader("referer");
    //   log.info("待转向URL:"+request.getHeader("referer"));
    if (url == null || url.equals("")) {
      url = "";
      String path = request.getContextPath();
      String actionName = invocation.getProxy().getActionName();
      String nameSpace = invocation.getProxy().getNamespace();
      if (!nameSpace.equals(null)) {
        url = url + path + nameSpace;
      }
      if (!actionName.equals(null)) {
        url = url + "/" + actionName + ".action" + "?";
      }

      Map<String, String[]> zzMap = request.getParameterMap();
      if (zzMap != null) {
        for (String s : zzMap.keySet()) {
          String[] value = zzMap.get(s);
          for (String val : value) {
            url = url + s + "=" + val + "&";
          }
        }
      }
      //   log.info("完整URL:"+url);
    }
    session.setAttribute("GOING_TO", url);
  }
  public String intercept(ActionInvocation invocation) throws Exception {
    User user = null;
    HttpServletRequest request = ServletActionContext.getRequest();
    int messageCount;
    userService.setSessionFactory(sessionFactory);
    user = (User) request.getSession().getAttribute("user");
    if (user == null) {
      System.out.println("redirecting to login");
      return MUST_AUTHENTICATE;
    } else {
      invocation.getStack().setValue("user", user);

      List<Message> messages = messageService.findCountByType(user.getCompanyId());
      long totalCount = 0;
      for (int i = 0; i < messages.size(); i++) {
        if (messages.get(i).getType().compareTo("RFQ") == 0) {
          request.getSession().putValue("rfqMessageCount", messages.get(i).getCount());
        } else if (messages.get(i).getType().compareTo("USER") == 0) {
          request.getSession().putValue("userMessageCount", messages.get(i).getCount());
        }
        totalCount += messages.get(i).getCount();
      }
      request.getSession().putValue("totalMessageCount", totalCount);
      return invocation.invoke();
    }
  }
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    String methodName = invocation.getProxy().getMethod();
    Class clazz = invocation.getAction().getClass(); // 获取类对象
    Method currentMethod = clazz.getMethod(methodName); // 获取拦截的方法

    // 方法上添加了注解
    if (currentMethod.isAnnotationPresent(Authority.class)) {
      // 取得当前请求的注解的action
      ActionContext context = invocation.getInvocationContext();
      Map session = context.getSession();
      // Constants.UserName=="UserName"
      String user = (String) session.get(Constants.UserName);

      // System.err.println("拦截器起作用");
      if (user == null) // 未登陆,跳转到登录页
      {
        // System.err.println("进入拦截器:未登陆");
        context.put("tip", "你还没有登录");
        return Action.LOGIN;
      } else { // 已登录,继续后续流程
        // System.err.println("进入拦截器:已登录");
        return invocation.invoke();
      }
    } else {
      // System.err.println("进入拦截器:没有使用注解");
      return invocation.invoke();
    }
  }
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    String result;

    try {
      result = invocation.invoke();
    } catch (Exception e) {
      if (isLogEnabled()) {
        handleLogging(e);
      }
      List<ExceptionMappingConfig> exceptionMappings =
          invocation.getProxy().getConfig().getExceptionMappings();
      ExceptionMappingConfig mappingConfig = this.findMappingFromExceptions(exceptionMappings, e);
      if (mappingConfig != null && mappingConfig.getResult() != null) {
        Map parameterMap = mappingConfig.getParams();
        // create a mutable HashMap since some interceptors will remove parameters, and parameterMap
        // is immutable
        invocation.getInvocationContext().setParameters(new HashMap<String, Object>(parameterMap));
        result = mappingConfig.getResult();
        publishException(invocation, new ExceptionHolder(e));
      } else {
        throw e;
      }
    }

    return result;
  }
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    Map<String, Object> session = invocation.getInvocationContext().getSession();
    User user = (User) session.get("user");

    HttpServletRequest request =
        (HttpServletRequest) invocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);

    if (user != null) {
      return invocation.invoke();
    } else {
      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember-me")) {
            Map<String, String> loginParameters =
                Splitter.on('&').withKeyValueSeparator('=').split(cookie.getValue());
            UserDao userDao = new UserDaoImpl();
            user = userDao.loginUser(loginParameters.get("email"), loginParameters.get("password"));
            if (!loginParameters.get("password").equals(user.getPassword())) {
              return "login";
            } else {
              session.put("user", user);
              request.setAttribute("rememberMe", "true");
              return invocation.invoke();
            }
          }
        }
      }
      return "login";
    }
  }
 @Override
 public String intercept(ActionInvocation invocation) throws Exception {
   String result = "";
   try {
     result = invocation.invoke();
     try {
       // 获取拦截方法
       Method method = getInvacotionMethod(invocation);
       // 已save update del 开头的方法
       if (method != null && Pattern.matches("^(save|update|del).*$", method.getName())) {
         EventDescription des = method.getAnnotation(EventDescription.class);
         String ipAddress = ServletActionContext.getRequest().getRemoteAddr();
         // 保存操作日志
         ActionEventLog log = new ActionEventLog();
         log.setEventDes(des != null ? des.value() : method.getName());
         log.setOperator(WebContext.getCurrentUser().getUser().getName());
         log.setArgs(JSON.toJSONString(invocation.getInvocationContext().getParameters()));
         log.setOperateDate(new Date());
         log.setIpAddress(ipAddress);
         DAO dao = (DAO) getSpringApplicationContext().getBean("platformDao");
         dao.create(log);
       }
     } catch (Exception e) {
       result = "exception";
       throw new BizException(e.getMessage());
     }
   } catch (Exception ex) {
     result = "exception";
     // handlingException(invocation, ex);
     ex.printStackTrace();
     throw new BizException(ex.getMessage());
   }
   return result;
 }
 @Override
 public String doIntercept(ActionInvocation invocation) throws Exception {
   Object action = invocation.getAction();
   if (action instanceof Preparable) {
     if (alwaysInvokePrepare) {
       ((Preparable) action).prepare();
     }
     try {
       String[] prefixes = new String[] {PREPARE_PREFIX};
       PrefixMethodInvocationUtil.invokePrefixMethod(invocation, prefixes);
     } catch (InvocationTargetException e) {
       /*
        * The invoked method threw an exception and reflection wrapped it
        * in an InvocationTargetException.
        * If possible re-throw the original exception so that normal
        * exception handling will take place.
        */
       Throwable cause = e.getCause();
       if (cause instanceof Exception) {
         throw (Exception) cause;
       } else if (cause instanceof Error) {
         throw (Error) cause;
       } else {
         /*
          * The cause is not an Exception or Error (must be Throwable) so
          * just re-throw the wrapped exception.
          */
         throw e;
       }
     }
   }
   return invocation.invoke();
 }
 public String intercept(ActionInvocation invocation) throws Exception {
   // 将一个拦截结果的监听器注册给该拦截器
   invocation.addPreResultListener(new MyPreResultListener());
   System.out.println("execute方法执行之前的拦截...");
   // 调用下一个拦截器,或者Action的执行方法
   String result = invocation.invoke();
   System.out.println("execute方法执行之后的拦截...");
   return result;
 }
Exemple #15
0
 @Override
 public String intercept(ActionInvocation ai) throws Exception {
   if (checkLegal(ai, ai.getProxy().getActionName())) {
     if (checkNeedUpdatePsw(ai, ai.getProxy().getActionName())) {
       return "login";
     }
     return ai.invoke();
   }
   return "login";
 }
  public void testActionContextLocaleIsPreservedWhenNotOverridden() throws Exception {
    final Locale locale1 = Locale.TRADITIONAL_CHINESE;
    mai.getInvocationContext().setLocale(locale1);
    interceptor.intercept(mai);

    Locale locale = (Locale) session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE);
    assertNull(locale); // should not be stored here
    locale = mai.getInvocationContext().getLocale();
    assertEquals(locale1, locale);
  }
  public void testIncludeParameterInResult() throws Exception {

    ResultConfig resultConfig =
        new ResultConfig.Builder("", "")
            .addParam("actionName", "someActionName")
            .addParam("namespace", "someNamespace")
            .addParam("encode", "true")
            .addParam("parse", "true")
            .addParam("location", "someLocation")
            .addParam("prependServletContext", "true")
            .addParam("method", "someMethod")
            .addParam("param1", "value 1")
            .addParam("param2", "value 2")
            .addParam("param3", "value 3")
            .addParam("anchor", "fragment")
            .build();

    ActionContext context = ActionContext.getContext();
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();
    context.put(ServletActionContext.HTTP_REQUEST, req);
    context.put(ServletActionContext.HTTP_RESPONSE, res);

    Map<String, ResultConfig> results = new HashMap<String, ResultConfig>();
    results.put("myResult", resultConfig);

    ActionConfig actionConfig =
        new ActionConfig.Builder("", "", "").addResultConfigs(results).build();

    ServletActionRedirectResult result = new ServletActionRedirectResult();
    result.setActionName("myAction");
    result.setNamespace("/myNamespace");
    result.setParse(false);
    result.setEncode(false);
    result.setPrependServletContext(false);
    result.setAnchor("fragment");
    result.setUrlHelper(new DefaultUrlHelper());

    IMocksControl control = createControl();
    ActionProxy mockActionProxy = control.createMock(ActionProxy.class);
    ActionInvocation mockInvocation = control.createMock(ActionInvocation.class);
    expect(mockInvocation.getProxy()).andReturn(mockActionProxy);
    expect(mockInvocation.getResultCode()).andReturn("myResult");
    expect(mockActionProxy.getConfig()).andReturn(actionConfig);
    expect(mockInvocation.getInvocationContext()).andReturn(context);

    control.replay();
    result.setActionMapper(container.getInstance(ActionMapper.class));
    result.execute(mockInvocation);
    assertEquals(
        "/myNamespace/myAction.action?param1=value+1&param2=value+2&param3=value+3#fragment",
        res.getRedirectedUrl());

    control.verify();
  }
 @Override
 public String intercept(ActionInvocation invocation) throws Exception {
   System.out.println("actionName" + invocation.getAction().getClass().getName());
   String name = (String) invocation.getStack().findString("username");
   System.out.println(name);
   if (name == null || "123".equals(name)) {
     System.out.println("fail");
     return "fail";
   }
   return invocation.invoke();
 }
 @Override
 public String intercept(ActionInvocation invocation) throws Exception {
   HttpServletRequest request = ServletActionContext.getRequest();
   RequestContext reqCtx = (RequestContext) request.getAttribute(RequestContext.REQCTX);
   if (null != reqCtx) {
     Lang currentLang = (Lang) reqCtx.getExtraParam(SystemConstants.EXTRAPAR_CURRENT_LANG);
     Locale locale = new Locale(currentLang.getCode(), "");
     invocation.getInvocationContext().setLocale(locale);
   }
   return invocation.invoke();
 }
 @Override
 public String intercept(ActionInvocation invocation) throws Exception {
   // TODO Auto-generated method stub
   ActionContext actionContext = invocation.getInvocationContext();
   Map<String, Object> map = actionContext.getParameters();
   for (Map.Entry<String, Object> entry : map.entrySet()) {
     String value = ((String[]) (entry.getValue()))[0];
     entry.setValue(StringEscapeUtils.escapeHtml4(value));
   }
   return invocation.invoke();
 }
 @Override
 public String intercept(ActionInvocation invocation) throws Exception {
   logger.debug("intercept start");
   try {
     ActionSupport action = (ActionSupport) invocation.getAction();
     action.clearErrors();
     return invocation.invoke();
   } finally {
     logger.debug("intercept end");
   }
 }
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    // TODO Auto-generated method stub
    InterUser interUser = new ImplUser();
    List alluserList = interUser.findAllUsers();
    List alladminList = interUser.findAllAdmins();

    invocation.getInvocationContext().getSession().put("alladminList", alladminList);
    invocation.getInvocationContext().getSession().put("alluserList", alluserList);

    return invocation.invoke();
  }
 @Override
 public String intercept(ActionInvocation ai) throws Exception {
   Map session = ai.getInvocationContext().getSession();
   String userEmail = (String) session.get("activeUser");
   if (userEmail != null && userEmail.length() > 0) {
     return ai.invoke();
   } else {
     ActionContext ac = ai.getInvocationContext();
     ac.put("popedom", "not login!");
     return "notLogin";
   }
 }
Exemple #24
0
  @Override
  public String intercept(ActionInvocation arg0) throws Exception {
    ActionContext actionContext = arg0.getInvocationContext();
    Map session = actionContext.getSession();
    User user = (User) session.get("user");

    if (user != null) {
      // System.out.println("+++++已登录+++++");
      return arg0.invoke();
    }
    // System.out.println("+++++未登录+++++");
    return Action.LOGIN;
  }
 public String intercept(ActionInvocation invocation) throws Exception {
   HttpServletRequest request = ServletActionContext.getRequest();
   HttpServletResponse response = ServletActionContext.getResponse();
   if (!isProperlyConfigured) {
     throw new IllegalArgumentException(
         "RolesInterceptor is misconfigured, check logs for erroneous configuration!");
   }
   if (!isAllowed(request, invocation.getAction())) {
     return handleRejection(invocation, response);
   } else {
     return invocation.invoke();
   }
 }
  public String intercept(ActionInvocation invocation) throws Exception {
    Object action = invocation.getAction();

    if (action instanceof FieldValidationAware) {
      FieldValidationAware fieldValidationAware = (FieldValidationAware) action;

      if (fieldValidationAware.hasErrors()) {
        return inputResultName;
      }
    }

    return invocation.invoke();
  }
 @Override
 public String intercept(ActionInvocation arg0) throws Exception {
   // TODO Auto-generated method stub
   Map session = arg0.getInvocationContext().getSession();
   User user = (User) session.get("user");
   if (null != user) {
     System.out.println("OK");
     return arg0.invoke();
   } else {
     System.out.print("login");
     return "error";
   }
 }
  @Override
  protected void setUp() throws Exception {
    contextMap = new LinkedHashMap();
    context = new ActionContext(contextMap);

    actionInvocationControl = MockControl.createControl(ActionInvocation.class);
    actionInvocation = (ActionInvocation) actionInvocationControl.getMock();
    actionInvocationControl.expectAndDefaultReturn(
        actionInvocation.getAction(), new SampleAction());
    actionInvocationControl.expectAndDefaultReturn(
        actionInvocation.getInvocationContext(), context);
    actionInvocationControl.expectAndDefaultReturn(actionInvocation.invoke(), "success");
  }
 @SuppressWarnings("unchecked")
 @Override
 // µÇ¼À¹½ØÆ÷
 public String intercept(ActionInvocation invocation) throws Exception {
   ActionContext context = invocation.getInvocationContext();
   Map session = context.getSession();
   User user = (User) session.get("user");
   if (user != null) {
     return invocation.invoke();
   }
   context.put("message", "Äú»¹Ã»ÓеǼ£¬ÇëµÇ¼ϵͳ¡£");
   return Action.LOGIN;
 }
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    Map<String, Object> session = invocation.getInvocationContext().getSession();
    Object inSessionObj = session.get("inSession");
    System.out.println("working in LoginCheckInterceptor with sess obj: " + inSessionObj);
    if ((Boolean) inSessionObj) {
      System.out.println("user is in session");
      return invocation.invoke();

    } else {
      return Action.LOGIN;
    }
  }