Example #1
0
 // 导出excel
 public void getExcelCreate() throws Exception {
   ActionContext ctx = ActionContext.getContext();
   HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
   HttpServletResponse response =
       (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);
   HttpSession session = request.getSession();
   User user = (User) session.getAttribute(Constants.userKey);
   try {
     String bbmc = request.getParameter("bbmc");
     String tabletitle = request.getParameter("tabletitle");
     // Excel输出
     List lResult = new ArrayList(); // //开头excel
     List gzdxList = (List) session.getAttribute("gzdxExportResult");
     Gzdx setGzdx = new Gzdx();
     List lColumn = this.getExcelColumn(tabletitle);
     lResult.add(bbmc);
     lResult.add(lColumn);
     lResult.add(response);
     lResult.add(gzdxList);
     lResult.add(setGzdx);
     this.setExcelCreate("gzdx", lResult);
     this.result = "ok";
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     this.result = e.getMessage();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     this.result = e.getMessage();
   }
 }
 public void init() {
   ActionContext act = ActionContext.getContext();
   request = (HttpServletRequest) act.get(ServletActionContext.HTTP_REQUEST);
   response = (HttpServletResponse) act.get(ServletActionContext.HTTP_RESPONSE);
   response.setContentType("text/html"); // 设置返回相应格式,很重要
   response.setCharacterEncoding("utf-8");
 }
Example #3
0
  public String login() {
    System.out.println("Entered login" + "\n");
    ActionContext ac = ActionContext.getContext();

    Map session = (Map) ac.get("com.opensymphony.xwork2.ActionContext.session");
    HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
    AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
    if (principal != null) {
      this.username = principal.getName();
      System.out.println("CAS获得username:" + username + "\t"); // 20068001171	null
      ActionContext.getContext().getSession().put("username", this.username);
      if (username != null
          && session != null
          && (session.get("username") != null)
          && (session.get("role") != null)) {
        if (ActionContext.getContext().getSession().get("role").equals("0")) {
          return "adminLogin";
        }
        if (ActionContext.getContext().getSession().get("role").equals("1")) {
          return "role1Login";
        }
      } else { // 输入工号密码时先跳至此处

        LoginService loginservice = new LoginService();
        Login lgn = loginservice.queryBy(username, "stuid");
        if (lgn != null) { // 管理员登录
          this.role = lgn.getRole();
          System.out.print("admin刚刚登录,Role:" + role + "\t");
        } else { // 普通学生
          XjbService xjbservice = new XjbService();
          Xjb xjb = xjbservice.queryBy(this.username, "是", "是"); // 是否有学籍,是否由国家学籍
          if (xjb != null) { // 有记录才可使用
            this.role = "1";
          } else {
            message = "只有在校本科生才可使用本系统!";
            return "input";
          }
        }
        System.out.println(username + "\t");
        ActionContext.getContext().getSession().put("username", this.username);
        ActionContext.getContext().getSession().put("role", role);
        if (this.role.equals("0")) {
          return "adminLogin";
        }
        if (this.role.equals("1")) {
          return "role1Login";
        }
      }
    }
    message = "您还未登录";
    return "input";
  }
  /**
   * 从cookie中读入登录信息。并写入到logincontext中。 只有登录成功后,才写入
   *
   * @param invocation
   * @return
   * @throws Exception
   */
  public String intercept(ActionInvocation invocation) throws Exception {

    ActionContext actionContext = invocation.getInvocationContext();
    HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
    HttpServletResponse response =
        (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);

    try {
      updateCookie(request, response);
    } catch (Exception e) {
      log.warn("update cookie error!", e);
    }

    return invocation.invoke();
  }
  public String intercept(ActionInvocation invocation) throws Exception {
    ActionContext context = ActionContext.getContext();
    String action = context.getName();
    //	context.get(ServletActionContext.APPLICATION);

    HttpServletRequest request =
        (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
    String ip =
        ((HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST)).getRemoteAddr();
    LOG.info("IP::" + ip + " visit the action:" + action + ",URL=" + request.getRequestURI());
    // 最理想的,在这里,通过这个url从数据库找到对应的rightcode。从而在代码中免除设置rightcode
    // 有个问题,abc!input.pl实际上是等于abc.pl的.一个是入口,一个是保存

    // webcontext初始化的时候,得到系统所有的rightcode到内存中
    return invocation.invoke();
  }
  /**
   * 方法用途和描述: 数据权限拦截器,将获取到的数据权限设置给action
   *
   * @author dongshen
   * @return
   * @since dongshen
   */
  public String intercept(ActionInvocation invocation) throws Exception {
    ActionContext actionContext = invocation.getInvocationContext();
    log.debug(
        "---AuthenticationInterceptor----"
            + invocation.getAction()
            + "!"
            + invocation.getResultCode());

    Object action = invocation.getAction();
    if (action instanceof BaseAction) {
      @SuppressWarnings("rawtypes")
      BaseAction baseAction = (BaseAction) action;
      HttpServletRequest request =
          (HttpServletRequest) actionContext.get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
      HttpSession session = request.getSession();
      UserRightEntity tbUser =
          (UserRightEntity) session.getAttribute(SessionUtils.USER); // SessionUtils.getUser();
      if (tbUser == null) return invocation.invoke();
      // 将登录用户账号回传给页面
      baseAction.setAdminname(tbUser.getUserEntity().getAccouont());
      baseAction.setAdminrole(tbUser.getUserEntity().getTbRole().getNote());
    }
    log.debug("拦截器通过!");
    return invocation.invoke();
  }
Example #7
0
  @Override
  public String execute() throws Exception {

    ActionContext ctx = ActionContext.getContext();

    ServletContext sc = (ServletContext) ctx.get(ServletActionContext.SERVLET_CONTEXT);

    ApplicationContext appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

    CourseManagerImpl cmi = (CourseManagerImpl) appContext.getBean("CourseManagerImpl");
    StudentManagerImpl smi = (StudentManagerImpl) appContext.getBean("StuManagerImpl");

    List cmiList = cmi.getCourses();
    List smiList = smi.getStudents();

    Map cmiMap = new HashMap();
    Map smiMap = new HashMap();

    for (int i = 0; i < cmiList.size(); i++) {
      Course course = (Course) cmiList.get(i);
      cmiMap.put(course.getCoursId(), course.getCoursName());
    }

    for (int i = 0; i < smiList.size(); i++) {
      Student student = (Student) smiList.get(i);
      smiMap.put(student.getStuId(), student.getStuName());
    }

    ActionContext actionContext = ActionContext.getContext();
    Map session = actionContext.getSession();
    session.put("cmiMap", cmiMap);
    session.put("smiMap", smiMap);
    return SUCCESS;
  }
Example #8
0
  /* (non-Javadoc)
   * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
   */
  @SuppressWarnings("unchecked")
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    // TODO Auto-generated method stub
    String name = invocation.getInvocationContext().getName();

    if (name.equals("LoginIn")) {
      return invocation.invoke();
    } else {
      ActionContext ac = invocation.getInvocationContext();
      HttpServletRequest request = (HttpServletRequest) ac.get(StrutsStatics.HTTP_REQUEST);
      Map<String, Object> session = (Map<String, Object>) ac.get(ServletActionContext.SESSION);

      if (session != null && session.get(USER_SESSION_KEY) != null) {
        return invocation.invoke();
      }

      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (USER_COOKIE_KEY.equals(cookie.getName())) {
            String value = cookie.getValue();
            if (StringUtils.isNotBlank(value)) {
              String[] split = value.split("==");
              String username = split[0];
              String password = split[1];

              if (mUserService.validateUser(username, password) == 1) {
                session.put(USER_SESSION_KEY, username);
              }
            } else {
              setGoingToURL(session, invocation);
              return "login";
            }

            return invocation.invoke();
          }
        }
      }

      setGoingToURL(session, invocation);
      return "login";
    }
  }
Example #9
0
  private void zuQyzajbbgtj(List lQyzajbtj, Qyzajbtj qyzajbtj, String cityFlag) {
    String zagxjgdm = "";
    String qybm = "";
    ActionContext ctx = ActionContext.getContext();
    HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute(Constants.userKey);
    String departTemp = user.getDepartment().getDepartcode();

    if (lQyzajbtj != null && lQyzajbtj.size() > 0) {
      for (int i = 0; i < lQyzajbtj.size(); i++) {
        Qyzajbtj getQyzajbtj = (Qyzajbtj) lQyzajbtj.get(i);
        if (getQyzajbtj.getQybm() != null) {
          qybm = getQyzajbtj.getQybm();
        }
        if (getQyzajbtj.getGxdwdm() != null) {
          zagxjgdm = getQyzajbtj.getGxdwdm();
        } else if (getQyzajbtj.getFxjdm() != null) {
          zagxjgdm = getQyzajbtj.getFxjdm();
        } else if (getQyzajbtj.getDsjgdm() != null) {
          zagxjgdm = getQyzajbtj.getDsjgdm();
        } else {
          zagxjgdm = departTemp;
        }
        if ("1".equals(qyzajbtj.getGxdwbz())) {
          zagxjgdm = zagxjgdm.substring(0, 8);
        } else if ("1".equals(qyzajbtj.getFxjbz())) {
          zagxjgdm = zagxjgdm.substring(0, 6);
        } else if ("1".equals(qyzajbtj.getDsjgbz()) && "2".equals(cityFlag)) {
          zagxjgdm = zagxjgdm.substring(0, 4);
        } else {
          zagxjgdm = zagxjgdm.substring(0, 2);
        }
        getQyzajbtj.setYgdd(
            "<a href='#' class='hyperlink' onClick=queryzajbbg_qyjbxxlist('1','"
                + getQyzajbtj.getHylbdm()
                + "','"
                + zagxjgdm
                + "','"
                + qybm
                + "');>"
                + getQyzajbtj.getYgdd()
                + "</a>");
        getQyzajbtj.setYddg(
            "<a href='#' class='hyperlink' onClick=queryzajbbg_qyjbxxlist('2','"
                + getQyzajbtj.getHylbdm()
                + "','"
                + zagxjgdm
                + "','"
                + qybm
                + "');>"
                + getQyzajbtj.getYddg()
                + "</a>");
      }
    }
  }
  /**
   * Sets action properties based on the interfaces an action implements. Things like application
   * properties, parameters, session attributes, etc are set based on the implementing interface.
   *
   * @param invocation an encapsulation of the action execution state.
   * @throws Exception if an error occurs when setting action properties.
   */
  public String intercept(ActionInvocation invocation) throws Exception {
    final Object action = invocation.getAction();
    final ActionContext context = invocation.getInvocationContext();

    if (action instanceof ServletRequestAware) {
      HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
      ((ServletRequestAware) action).setServletRequest(request);
    }

    if (action instanceof ServletResponseAware) {
      HttpServletResponse response = (HttpServletResponse) context.get(HTTP_RESPONSE);
      ((ServletResponseAware) action).setServletResponse(response);
    }

    if (action instanceof ParameterAware) {
      ((ParameterAware) action).setParameters(context.getParameters());
    }

    if (action instanceof ApplicationAware) {
      ((ApplicationAware) action).setApplication(context.getApplication());
    }

    if (action instanceof SessionAware) {
      ((SessionAware) action).setSession(context.getSession());
    }

    if (action instanceof RequestAware) {
      ((RequestAware) action).setRequest((Map) context.get("request"));
    }

    if (action instanceof PrincipalAware) {
      HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
      if (request != null) {
        // We are in servtlet environment, so principal information resides in HttpServletRequest
        ((PrincipalAware) action).setPrincipalProxy(new ServletPrincipalProxy(request));
      }
    }
    if (action instanceof ServletContextAware) {
      ServletContext servletContext = (ServletContext) context.get(SERVLET_CONTEXT);
      ((ServletContextAware) action).setServletContext(servletContext);
    }
    return invocation.invoke();
  }
Example #11
0
 // 企业治安级别统计查询
 public String querylist() throws Exception {
   try {
     Qyzajbtj setQyzajbtj = new Qyzajbtj();
     setQyzajbtj = (Qyzajbtj) this.setClass(setQyzajbtj, null);
     Map map = new HashMap();
     map.put("dsjgbz", setQyzajbtj.getDsjgbz());
     map.put("fxjbz", setQyzajbtj.getFxjbz());
     map.put("gxdwbz", setQyzajbtj.getGxdwbz());
     map.put("csbz", setQyzajbtj.getCsbz());
     map.put("dsjgdm", setQyzajbtj.getDsjgdm());
     map.put("fxjdm", setQyzajbtj.getFxjdm());
     map.put("gxdwdm", setQyzajbtj.getGxdwdm());
     map.put("qybm", setQyzajbtj.getCsbm());
     map.put("qssj", setQyzajbtj.getQssj());
     map.put("jzsj", setQyzajbtj.getJzsj());
     map.put("hylbdm", setQyzajbtj.getHylbdm());
     ActionContext ctx = ActionContext.getContext();
     HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
     HttpSession session = request.getSession();
     User user = (User) session.getAttribute(Constants.userKey);
     String departTemp = user.getDepartment().getDepartcode();
     String sjName = ""; // 市局名称(直辖市)
     String cityFlag = "1";
     if (departTemp.substring(0, 2).equals("11")) {
       sjName = "北京市公安局";
       map.put("cityFlag", "1");
     } else if (departTemp.substring(0, 2).equals("12")) {
       sjName = "天津市公安局";
       map.put("cityFlag", "1");
     } else if (departTemp.substring(0, 2).equals("31")) {
       sjName = "上海市公安局";
       map.put("cityFlag", "1");
     } else if (departTemp.substring(0, 2).equals("50")) {
       sjName = "重庆市公安局";
       map.put("cityFlag", "1");
     } else {
       cityFlag = "2";
     }
     Page page = qyzajbtjService.getQyzajbtjList(map, pagesize, pagerow, sort, dir);
     totalpage = page.getTotalPages();
     totalrows = page.getTotalRows();
     lQyzajbtj = page.getData();
     zuQyzajbtj(lQyzajbtj, setQyzajbtj, cityFlag);
     this.result = "success";
   } catch (Exception e) {
     this.result = "查询列表失败";
     e.printStackTrace();
   }
   return "success";
 }
Example #12
0
 /**
  * 导出入口
  *
  * @param exportType 导出文件的类型
  * @param jaspername jasper文件的名字 如: xx.jasper
  * @param lists 导出的数据
  * @param request
  * @param response
  * @param defaultFilename默认的导出文件的名称
  */
 public static void exportmain(
     String exportType, String jaspername, List lists, String defaultFilename) {
   logger.debug("进入导出    The method======= exportmain() start.......................");
   ActionContext ct = ActionContext.getContext();
   HttpServletRequest request = (HttpServletRequest) ct.get(ServletActionContext.HTTP_REQUEST);
   HttpServletResponse response = ServletActionContext.getResponse();
   String filenurl =
       request.getRealPath("/report/" + jaspername); // jasper文件放在WebRoot/ireport/xx.jasper</span>
   File file = new File(filenurl);
   InputStream is = null;
   try {
     is = new FileInputStream(file);
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
   export(lists, exportType, defaultFilename, is, request, response);
 }
Example #13
0
  public String doIntercept(ActionInvocation invocation) throws Exception {

    if (log.isDebugEnabled()) {
      log.debug("Entering UIActionInterceptor");
    }

    final Object action = invocation.getAction();
    final ActionContext context = invocation.getInvocationContext();

    HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);

    // is this one of our own UIAction classes?
    if (action instanceof UIAction) {

      if (log.isDebugEnabled()) {
        log.debug("action is a UIAction, setting relevant attributes");
      }

      UIAction theAction = (UIAction) action;

      // extract the authenticated user and set it
      RollerSession rses = RollerSession.getRollerSession(request);
      if (rses != null) {
        theAction.setAuthenticatedUser(rses.getAuthenticatedUser());
      }

      // extract the work weblog and set it
      String weblogHandle = theAction.getWeblog();
      if (!StringUtils.isEmpty(weblogHandle)) {
        Weblog weblog = null;
        try {
          weblog =
              WebloggerFactory.getWeblogger().getWeblogManager().getWeblogByHandle(weblogHandle);
          if (weblog != null) {
            theAction.setActionWeblog(weblog);
          }
        } catch (Exception e) {
          log.error("Error looking up action weblog - " + weblogHandle, e);
        }
      }
    }

    return invocation.invoke();
  }
Example #14
0
  public String addJson() {
    try {
      ActionContext ctx = ActionContext.getContext();
      HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
      BufferedInputStream inputStream = new BufferedInputStream(request.getInputStream());

      FpageEvent fpageEvent = new FpageEvent();
      fpageEvent.setIssueId(issueId);
      // fpageEvent.setPublicationId(issueService.queryById(issueId).getPublicationId());
      fpageEvent.setPageNo(start);
      fpageEvent.setEndPageNo(end);
      fpageEvent.setDescription(description);
      fpageEvent.setTitle(title);
      if (description != null) {
        fpageEvent.setDescription(java.net.URLDecoder.decode(description));
      }
      if (title != null) {
        fpageEvent.setTitle(java.net.URLDecoder.decode(title));
      }
      fpageEvent.setWidth(width);
      fpageEvent.setHeight(height);
      fpageEvent.setAdId(adId);
      System.out.println("--->:" + tagStr);
      String[] arr = null;
      if (StringUtil.isNotBlank(tagStr)) { // 添加标签(事件)
        tagStr = java.net.URLDecoder.decode(tagStr);
        arr = tagStr.split(";");
      }

      this.jsonResult =
          fpageEventService.addJson(
              fpageEvent,
              inputStream,
              (Admin) ctx.getSession().get(WebConstant.SESSION.ADMIN),
              arr);

    } catch (Exception e) {
      e.printStackTrace();
      this.generateJsonResult(JsonResult.CODE.EXCEPTION, "服务器内部错误");
    }
    return JSON;
  }
  public void testResolveModel() throws Exception {
    ActionContext ctx = ActionContext.getContext();
    ctx.setSession(new HashMap());

    ObjectFactory factory = ObjectFactory.getObjectFactory();
    Object obj = inter.resolveModel(factory, ctx, "java.lang.String", "request", "foo");
    assertNotNull(obj);
    assertTrue(obj instanceof String);
    assertTrue(obj == ctx.get("foo"));

    obj = inter.resolveModel(factory, ctx, "java.lang.String", "session", "foo");
    assertNotNull(obj);
    assertTrue(obj instanceof String);
    assertTrue(obj == ctx.getSession().get("foo"));

    obj = inter.resolveModel(factory, ctx, "java.lang.String", "session", "foo");
    assertNotNull(obj);
    assertTrue(obj instanceof String);
    assertTrue(obj == ctx.getSession().get("foo"));
  }
Example #16
0
 @Override
 public String intercept(ActionInvocation actionInvocation) throws Exception {
   final ActionContext context = actionInvocation.getInvocationContext();
   HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
   String[] urlX = ("" + request.getRequestURL()).split("\\?");
   String[] url = urlX[0].split("/");
   String url2 = url[url.length - 1];
   System.out.println("URL invocated: " + url2);
   String usuario = (String) request.getSession().getAttribute("usuario");
   String foward = "logon";
   if (usuario != null) {
     boolean continuar = securityInterceptorLogic.getUrlAccess(usuario, url2);
     if (continuar) {
       return actionInvocation.invoke();
     } else {
       request.getSession().setAttribute("mensajeError", "No tiene acceso a esta opcion");
       return "error";
     }
   }
   return foward;
 }
  protected ClassLoaderInterface getClassLoaderInterface() {

    /*
    if there is a ClassLoaderInterface in the context, use it, otherwise
    default to the default ClassLoaderInterface (a wrapper around the current
    thread classloader)
    using this, other plugins (like OSGi) can plugin their own classloader for a while
    and it will be used by Convention (it cannot be a bean, as Convention is likely to be
    called multiple times, and it need to use the default ClassLoaderInterface during normal startup)
    */
    ClassLoaderInterface classLoaderInterface = null;
    ActionContext ctx = ActionContext.getContext();
    if (ctx != null)
      classLoaderInterface =
          (ClassLoaderInterface) ctx.get(ClassLoaderInterface.CLASS_LOADER_INTERFACE);

    return (ClassLoaderInterface)
        ObjectUtils.defaultIfNull(
            classLoaderInterface,
            new ClassLoaderInterfaceDelegate(Thread.currentThread().getContextClassLoader()));
  }
Example #18
0
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {

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

    Map session = actionContext.getSession();
    UserInfo ui = (UserInfo) session.get(ONLINE_USER);

    if (ui != null) {
      String url = request.getRequestURI();
      /**
       * String queryString = request.getQueryString(); if (queryString != null &&
       * queryString.indexOf("input=true&vehicleId") >= 0) { //不做记录 } else {
       *
       * <p>int index = url.lastIndexOf('/') + 1;
       *
       * <p>String actionName = url.substring(index);
       *
       * <p>OperationLog ol = new OperationLog(); ol.setUserId(ui.getEntityId());
       * ol.setUserName(ui.getName()); ol.setDetail(actionName); ol.setUrl(url);
       * ol.setIp(request.getRemoteAddr()); try { baseDao.save(ol); } catch (Exception ex) {
       * log.error(ex.getMessage(), ex); } }
       */
      return invocation.invoke();
    }

    /**
     * Cookie[] cookies = request.getCookies(); if (cookies!=null) { for (Cookie cookie : cookies) {
     * if (COOKIE_REMEMBERME_KEY.equals(cookie.getName())) { String value = cookie.getValue(); if
     * (StringUtils.isNotBlank(value)) { String[] split = value.split("=="); String userName =
     * split[0]; String password = split[1]; try { User user = userDao .attemptLogin(userName,
     * password); session.put(USER_SESSION_KEY, user); } catch (UserNotFoundException e) {
     * setGoingToURL(session, invocation); return "login"; } } else { setGoingToURL(session,
     * invocation); return "login"; } return invocation.invoke(); } } } setGoingToURL(session,
     * invocation);
     */
    return "login";
  }
 public String execute() throws Exception {
   try {
     // 取得请求相关的ActionContext实例
     ActionContext context = ActionContext.getContext();
     HttpServletRequest httpRequest = (HttpServletRequest) context.get(HTTP_REQUEST);
     // 校验验证码是否已超时
     boolean checkVerifyCodeTime = canPassTimeOut(httpRequest);
     if (!checkVerifyCodeTime) {
       logger.error("验证码已超时");
       throw new ServiceException(AppErrorCodeConstants.EBNT10024);
     }
     // 校验验证码
     boolean checkVerifyCodeResult = canPass(httpRequest, this.checkCode);
     if (!checkVerifyCodeResult) {
       logger.error("验证码不正确");
       throw new ServiceException(AppErrorCodeConstants.EBNT10025);
     }
   } catch (Exception ex) {
     this.handleError(ex);
   }
   return SUCCESS;
 }
Example #20
0
  @Override
  public String execute() throws Exception {
    // TODO Auto-generated method stub
    // 获取作用域中的Map对象

    // ServletActionContext

    ActionContext actionContext = ActionContext.getContext();

    Map<String, Object> sessionMap = actionContext.getSession();

    Map<String, Object> appMap = actionContext.getApplication();

    // 不建议用map对象去获取request作用域的数据
    Map<String, Object> requestMap = (Map<String, Object>) actionContext.get("request");

    sessionMap.put("ses_key", "session中的数据");

    appMap.put("app_key", "application作用域中的数据");

    requestMap.put("req_key", "request作用域中的对象");

    return "scope2";
  }
Example #21
0
  public String execute() {
    System.out.println("Reported Date " + reportedDate);

    // Map<String, String> llElementValuesMap = new HashMap<String,
    // String>();
    List<LineListElement> lineListElements;

    List<LineListDataValue> llDataValuesList = new ArrayList<LineListDataValue>();
    List<LineListDataValue> llDataValuesUpdatedList = new ArrayList<LineListDataValue>();

    OrganisationUnit organisationUnit = selectedStateManager.getSelectedOrganisationUnit();

    // period = periodService.getPeriod(period.getStartDate(),
    // period.getEndDate(), period.getPeriodType());
    lineListGroup = selectedStateManager.getSelectedLineListGroup();

    Period period;

    if (lineListGroup != null
        && lineListGroup.getPeriodType().getName().equalsIgnoreCase("OnChange")) {
      period = periodService.getPeriod(0);
    } else {
      period = selectedStateManager.getSelectedPeriod();

      period = reloadPeriodForceAdd(period);
    }

    // String parts[] = dataElementId.split( ":" );

    ActionContext ctx = ActionContext.getContext();
    HttpServletRequest req = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
    session = req.getSession();

    int totalRecords = Integer.parseInt(req.getParameter("totalRecords"));
    int recordsFromDb = Integer.parseInt(req.getParameter("recordsFromDb"));

    lineListElements = new ArrayList<LineListElement>(lineListGroup.getLineListElements());

    String recordNumbersList = req.getParameter("recordNumbersList");
    System.out.println(recordNumbersList);
    // this code is for edited value saving
    String[] recordNos = recordNumbersList.split(":");
    for (int j = 0; j < recordNos.length; j++) {
      String recordNo = recordNos[j];
      System.out.println("recordNo = " + recordNo);
      if (!(recordNo.equals(""))) {
        String valueChangedName = "changedValue:" + recordNo;
        String valueChanged = req.getParameter(valueChangedName);
        if (!(valueChanged.equalsIgnoreCase(""))) {
          System.out.println("valueChanged = " + valueChanged);
          String[] elementNames = valueChanged.split(" ");
          LineListDataValue llDataValue = new LineListDataValue();
          Map<String, String> llElementValuesMap = new HashMap<String, String>();
          for (int e = 0; e < elementNames.length; e++) {
            String name = elementNames[e] + ":" + recordNo;
            String dataValue = req.getParameter(name);
            // System.out.println("name = " + name + " value  = " +
            // dataValue);
            if (dataValue != null && dataValue.trim().equals("")) {
              dataValue = "";
            }
            // if(dataValue.equals( "" ))
            llElementValuesMap.put(elementNames[e], dataValue);
            // System.out.println("llElementValuesMap size = "+
            // llElementValuesMap.size() + " key = "+elementNames[e]
            // + " value = "+llElementValuesMap.get( elementNames[e]
            // ));

          }

          // add map in linelist data value
          llDataValue.setLineListValues(llElementValuesMap);

          // add recordNumber to pass to the update query
          llDataValue.setRecordNumber(Integer.parseInt(recordNo));

          // add stored by, timestamp in linelist data value
          storedBy = currentUserService.getCurrentUsername();

          if (storedBy == null) {
            storedBy = "[unknown]";
          }

          llDataValue.setStoredBy(storedBy);

          if (reportedDate != null) {
            Date reportDate = format.parseDate(reportedDate);
            llDataValue.setTimestamp(reportDate);
          } else {
            llDataValue.setTimestamp(new Date());
          }

          llDataValuesUpdatedList.add(llDataValue);
        }
      }
    }

    // this code is for newly added values save
    while (recordsFromDb < totalRecords) {
      System.out.println("recordsFromDb = " + recordsFromDb);
      System.out.println("totalRecords = " + totalRecords);
      recordsFromDb++;
      LineListDataValue llDataValue = new LineListDataValue();
      Map<String, String> llElementValuesMap = new HashMap<String, String>();
      for (LineListElement element : lineListElements) {

        String name = element.getShortName() + ":" + recordsFromDb;
        String dataValue = req.getParameter(name);
        System.out.println("name = " + name + " value  = " + req.getParameter(name));

        if (dataValue != null && dataValue.trim().equals("")) {
          dataValue = "";
        }
        if (!(dataValue.equals(""))) llElementValuesMap.put(element.getShortName(), dataValue);
      }

      // add map in linelist data value
      llDataValue.setLineListValues(llElementValuesMap);

      // add period source, stored by, timestamp in linelist data value
      llDataValue.setPeriod(period);
      llDataValue.setSource(organisationUnit);

      storedBy = currentUserService.getCurrentUsername();

      if (storedBy == null) {
        storedBy = "[unknown]";
      }

      llDataValue.setStoredBy(storedBy);

      if (reportedDate != null && !reportedDate.trim().equalsIgnoreCase("")) {
        Date reportDate = format.parseDate(reportedDate);
        llDataValue.setTimestamp(reportDate);
      } else {
        llDataValue.setTimestamp(new Date());
      }

      llDataValuesList.add(llDataValue);
    }

    if (llDataValuesList.isEmpty() || llDataValuesList == null) {

      // deleteLLValue();

    } else {

      boolean valueInserted =
          dataBaseManagerInterface.insertLLValueIntoDb(
              llDataValuesList, lineListGroup.getShortName());
      System.out.println("valueInserted = " + valueInserted);
    }

    if (llDataValuesUpdatedList.isEmpty() || llDataValuesUpdatedList == null) {

    } else {
      boolean updateLLValue =
          dataBaseManagerInterface.updateLLValue(
              llDataValuesUpdatedList, lineListGroup.getShortName());
      System.out.println("updateLLValue = " + updateLLValue);
    }
    if (delRecordNo != null) {
      deleteLLValue();
    }
    return SUCCESS;
  }
 /**
  * 获取response 对象
  *
  * @return
  */
 public HttpServletResponse getResponse() {
   ActionContext context = ActionContext.getContext();
   HttpServletResponse response =
       (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);
   return response;
 }
 /**
  * 获取request对象
  *
  * @return
  */
 public HttpServletRequest getRequest() {
   ActionContext context = ActionContext.getContext();
   HttpServletRequest request =
       (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
   return request;
 }
@SuppressWarnings("serial")
@ParentPackage("struts-default")
@Namespace(value = "/")
@Component("contact-tListStatusTypeAction")
@Scope("prototype")
public class TListStatusTypeAction extends ActionSupport {

  private TListStatusTypeService tlstsService;
  private TListStatusService tlssSerivce;

  private String splitExp = "@#$";

  ActionContext actionContext = ActionContext.getContext();
  HttpServletRequest request =
      (HttpServletRequest) actionContext.get(ServletActionContext.HTTP_REQUEST);
  HttpServletResponse response =
      (HttpServletResponse) actionContext.get(ServletActionContext.HTTP_RESPONSE);

  @SuppressWarnings("unchecked")
  @Action(value = "listStatusTypeAction")
  public String listStatusType() {
    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");
    String parentCode = StringUtil.getNotNullValueString(request.getParameter("parentid"));
    String type = StringUtil.getNotNullValueString(request.getParameter("type"));
    List list = new ArrayList();
    // 判断此处是找TListStatusType的第一层节点,还是去找TListStatus的子节点
    Boolean firstLevel = tlssSerivce.findChildRecord(parentCode);
    Boolean otherLevel = tlssSerivce.Exist(parentCode);
    if (!firstLevel) {
      if (!otherLevel) {
        list = tlstsService.findAll(type);
      } else {
        list = tlssSerivce.findTListStatusByRefId(parentCode);
      }

    } else {
      list = tlssSerivce.findTListStatusByCode(parentCode);
    }

    Iterator iter = list.iterator();
    TListStatusType tempListStatusType = null;
    TListStatus tempListStatus = null;
    String temps = "";

    while (iter.hasNext()) {
      if (!firstLevel) {
        if (!otherLevel) {
          tempListStatusType = (TListStatusType) iter.next();

          String tmpVal =
              tempListStatusType.getCode()
                  + splitExp
                  + tempListStatusType.getName()
                  + splitExp
                  + tempListStatusType.getMemo()
                  + splitExp
                  + ""
                  + splitExp
                  + firstLevel.toString()
                  + splitExp
                  + otherLevel.toString()
                  + splitExp
                  + "root"
                  + "@|@";
          temps += tmpVal;
        } else {
          tempListStatus = (TListStatus) iter.next();
          String tmpVal =
              tempListStatus.getSid()
                  + splitExp
                  + tempListStatus.getContent()
                  + splitExp
                  + tempListStatus.getMemo()
                  + splitExp
                  + tempListStatus.getOptorder()
                  + splitExp
                  + firstLevel.toString()
                  + splitExp
                  + otherLevel.toString()
                  + splitExp
                  + "child"
                  + "@|@";
          temps += tmpVal;
        }
      } else {
        tempListStatus = (TListStatus) iter.next();
        String tmpVal =
            tempListStatus.getSid()
                + splitExp
                + tempListStatus.getContent()
                + splitExp
                + tempListStatus.getMemo()
                + splitExp
                + tempListStatus.getOptorder()
                + splitExp
                + firstLevel.toString()
                + splitExp
                + otherLevel.toString()
                + splitExp
                + "child1"
                + "@|@";
        temps += tmpVal;
      }
    }

    // String last_xml = xml;
    // System.out.println("==========" +temps + "============");
    Writer w = null;
    try {
      response.setCharacterEncoding("UTF-8");
      w = response.getWriter();
      w.write(temps);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (w != null) w.flush();
        if (w != null) w.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return null;
  }

  @Action(value = "saveDict")
  public String saveDict() {
    String code = StringUtil.getNotNullValueString(request.getParameter("code"));
    String name = StringUtil.getNotNullValueString(request.getParameter("name"));
    String memo = StringUtil.getNotNullValueString(request.getParameter("memo"));
    String flag = "false";
    if (tlstsService.ExistSameFaDict(code, name)) {
      Writer w = null;
      try {
        flag = "true";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        w = response.getWriter();
        w.write(flag);
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        try {
          if (w != null) w.flush();
          if (w != null) w.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    } else {

      // 保存一级科目信息

      TListStatusType tlst = new TListStatusType();
      // Date date=null;
      Calendar cl = Calendar.getInstance();
      cl.setTime(new java.util.Date());
      // date=cl.getTime();
      // SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      // String dateTime = time.format(date);//系统日期
      tlst.setCode(code);
      tlst.setName(name);
      tlst.setMemo(memo);
      tlst.setState("1");
      tlst.setUptdate(getCurrentTime());
      tlstsService.saveFaDict(tlst);
    }
    return null;
  }

  @Action(value = "saveChildDict")
  public String saveChildDict() {
    String xh = StringUtil.getNotNullValueString(request.getParameter("xh"));
    String name = StringUtil.getNotNullValueString(request.getParameter("name"));
    String memo = StringUtil.getNotNullValueString(request.getParameter("memo"));
    String sid = StringUtil.getNotNullValueString(request.getParameter("sid"));
    String belongKindCode = request.getParameter("belongKindCode");
    Date date = null;
    Calendar cl = Calendar.getInstance();
    cl.setTime(new java.util.Date());
    date = cl.getTime();
    SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateTime = time.format(date); // 系统日期
    // 保存子科目

    if (tlstsService.ExistSameChildDict(name)) {
      TListStatus tls = new TListStatus();
      tls.setContent(name);
      if (!xh.equals("")) {
        tls.setOptorder(Integer.parseInt(xh));
      } else {
      }
      tls.setMemo(memo);
      tls.setState("1");
      tls.setUptdate(dateTime);
      tls.setInfotype(tlstsService.findTListStatusTypeByCode(belongKindCode));
      if (!sid.equals("")) {
        tls.setRefsid((TListStatus) tlssSerivce.findTListStatusBySID(sid).get(0));
      }
      tlssSerivce.saveChildListStatus(tls);
    } else {
      TListStatus tls = new TListStatus();
      tls.setContent(name);
      if (!xh.equals("")) {
        tls.setOptorder(Integer.parseInt(xh));
      } else {
      }
      tls.setMemo(memo);
      tls.setState("1");
      tls.setUptdate(dateTime);
      tls.setInfotype(tlstsService.findTListStatusTypeByCode(belongKindCode));
      if (!sid.equals("")) {
        tls.setRefsid((TListStatus) tlssSerivce.findTListStatusBySID(sid).get(0));
      }
      tlssSerivce.saveChildListStatus(tls);
      // 同样在T_LIST_TYPE中也要保存字典项,如果belongKindCode为JS_UnitType
      if (belongKindCode.equals("JS_UnitType")) {
        TListStatusType tlst = new TListStatusType();
        tlst.setCode("JS_" + name);
        tlst.setName(name + "字典项");
        tlst.setUptdate(getCurrentTime());
        tlst.setState("1");
        tlst.setMemo(memo);
        tlstsService.saveFaDict(tlst);
      }
    }

    return null;
  }

  @Action(value = "delDict")
  public String delDict() {
    String sid = request.getParameter("sid") == null ? "" : request.getParameter("sid");
    String code = request.getParameter("code") == null ? "" : request.getParameter("code");
    if (sid.equals("")) {
      if (tlstsService.exist(code)) {
        tlstsService.delRecord(code);
      }
    } else {
      if (tlstsService.exist(code) && tlssSerivce.Exist(sid)) {
        tlssSerivce.delRecord(sid);
      }
    }
    return null;
  }

  @Action(value = "modiDict")
  public String modiDict() {
    String sid = request.getParameter("sid") == null ? "" : request.getParameter("sid");
    String code = request.getParameter("code") == null ? "" : request.getParameter("code");
    String memo = request.getParameter("memo") == null ? "" : request.getParameter("memo");
    String name = request.getParameter("name") == null ? "" : request.getParameter("name");
    String xh = request.getParameter("xh") == null ? "" : request.getParameter("xh");
    if (sid.equals("") && !code.equals("")) {
      tlstsService.modiRecord(code, name, memo);
    } else if (!sid.equals("") && !code.equals("")) {
      tlssSerivce.modiRecord(sid, name, memo, xh);
    }
    return null;
  }

  public static String getCurrentTime() {
    return DateUtil.getCurrDate("yyyy-MM-dd HH:mm:ss");
  }

  public TListStatusTypeService getTlstsService() {
    return tlstsService;
  }

  @Autowired(required = false)
  public void setTlstsService(
      @Qualifier("contact-tListStatusTypeService") TListStatusTypeService tlstsService) {
    this.tlstsService = tlstsService;
  }

  public TListStatusService getTlssSerivce() {
    return tlssSerivce;
  }

  @Autowired(required = false)
  public void setTlssSerivce(
      @Qualifier("contact-tListStatusService") TListStatusService tlssSerivce) {
    this.tlssSerivce = tlssSerivce;
  }
}
  public String intercept(ActionInvocation invocation) throws Exception {
    ActionContext ac = invocation.getInvocationContext();

    HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);

    if (!(request instanceof MultiPartRequestWrapper)) {
      if (LOG.isDebugEnabled()) {
        ActionProxy proxy = invocation.getProxy();
        LOG.debug(
            getTextMessage(
                "struts.messages.bypass.request",
                new String[] {proxy.getNamespace(), proxy.getActionName()}));
      }

      return invocation.invoke();
    }

    ValidationAware validation = null;

    Object action = invocation.getAction();

    if (action instanceof ValidationAware) {
      validation = (ValidationAware) action;
    }

    MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;

    if (multiWrapper.hasErrors()) {
      for (String error : multiWrapper.getErrors()) {
        if (validation != null) {
          validation.addActionError(error);
        }

        if (LOG.isWarnEnabled()) {
          LOG.warn(error);
        }
      }
    }

    // bind allowed Files
    Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
    while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {
      // get the value of this input tag
      String inputName = (String) fileParameterNames.nextElement();

      // get the content type
      String[] contentType = multiWrapper.getContentTypes(inputName);

      if (isNonEmpty(contentType)) {
        // get the name of the file from the input tag
        String[] fileName = multiWrapper.getFileNames(inputName);

        if (isNonEmpty(fileName)) {
          // get a File object for the uploaded File
          File[] files = multiWrapper.getFiles(inputName);
          if (files != null && files.length > 0) {
            List<File> acceptedFiles = new ArrayList<File>(files.length);
            List<String> acceptedContentTypes = new ArrayList<String>(files.length);
            List<String> acceptedFileNames = new ArrayList<String>(files.length);
            String contentTypeName = inputName + "ContentType";
            String fileNameName = inputName + "FileName";

            for (int index = 0; index < files.length; index++) {
              if (acceptFile(
                  action,
                  files[index],
                  fileName[index],
                  contentType[index],
                  inputName,
                  validation)) {
                acceptedFiles.add(files[index]);
                acceptedContentTypes.add(contentType[index]);
                acceptedFileNames.add(fileName[index]);
              }
            }

            if (!acceptedFiles.isEmpty()) {
              Map<String, Object> params = ac.getParameters();

              params.put(inputName, acceptedFiles.toArray(new File[acceptedFiles.size()]));
              params.put(
                  contentTypeName,
                  acceptedContentTypes.toArray(new String[acceptedContentTypes.size()]));
              params.put(
                  fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()]));
            }
          }
        } else {
          if (LOG.isWarnEnabled()) {
            LOG.warn(
                getTextMessage(action, "struts.messages.invalid.file", new String[] {inputName}));
          }
        }
      } else {
        if (LOG.isWarnEnabled()) {
          LOG.warn(
              getTextMessage(
                  action, "struts.messages.invalid.content.type", new String[] {inputName}));
        }
      }
    }

    // invoke action
    return invocation.invoke();
  }
Example #26
0
  /*
   * (non-Javadoc)
   *
   * @seecom.opensymphony.xwork2.Result#execute(com.opensymphony.xwork2.
   * ActionInvocation)
   */
  @Override
  @SuppressWarnings("unused")
  public void execute(ActionInvocation invocation) throws Exception {

    ActionContext actionContext = invocation.getInvocationContext();

    HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
    HttpServletResponse response =
        (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);

    ValueStack vs = invocation.getStack();

    if (null == value) {
      return;
    }

    Object evaluated = vs.findValue(value);

    if (null == evaluated) {
      LOG.warn("value [" + value + "] is null in ValueStack. ");
      return;
    }

    try {

      if (isPrimitive(evaluated)) {
        //
        Map<String, Object> map = new HashMap<String, Object>(1);
        key = StringUtils.isBlank(key) ? value : StringUtils.trim(key);
        map.put(key, evaluated);
        evaluated = map;
      }

      GsonBuilder builder = new GsonBuilder();
      builder.registerTypeAdapter(
          DateTime.class,
          new JsonSerializer<DateTime>() {

            @Override
            public JsonElement serialize(DateTime arg0, Type arg1, JsonSerializationContext arg2) {
              return new JsonPrimitive(arg0.toString(DateFormatter.SDF_YMDHMS));
            }
          });

      Gson gson = builder.create();
      String json = gson.toJson(evaluated);

      if (StringUtils.isNotBlank(jsonpCallback)) {
        json = String.format("%s(%s);", jsonpCallback, json);
      }

      if (LOG.isDebugEnabled()) {
        LOG.debug("[JSON]\n" + json);
      }

      String encoding = getEncoding();
      String contentType = getContentType();
      if (encoding != null) {
        contentType = contentType + ";charset=" + encoding;
      }

      Writer writer = new OutputStreamWriter(response.getOutputStream(), encoding);
      try {
        response.setContentType(contentType);
        response.setContentLength(json.getBytes(defaultEncoding).length);
        writer.write(json);
      } finally {
        writer.close();
      }
    } catch (Exception e) {
      LOG.error("Unable to render json for value: '" + value + "'", e);
      throw e;
    } finally {
      //
    }

    return;
  }
Example #27
0
/**
 * @ClassName: OutputExcelAction @Description: TODO(导出excel)
 *
 * @author hukaimiao
 * @date 2014-9-11 下午4:16:55
 */
public class ManageExcelAction extends ActionSupport {

  /** @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么) */
  private static final long serialVersionUID = 1L;

  ActionContext cxt = ActionContext.getContext();
  HttpServletRequest request = (HttpServletRequest) cxt.get(ServletActionContext.HTTP_REQUEST);
  HttpServletResponse response = (HttpServletResponse) cxt.get(ServletActionContext.HTTP_RESPONSE);

  private List<Student> list;
  // 导出excel需要的变量
  private File excelFile; // 上传的文件

  private String excelFileFileName; // 保存原始文件名

  // 将Excel文件解析完毕后信息存放到这个对象中
  private ExcelWorkSheet<Student> excelWorkSheet;

  /**
   * 导出excel
   *
   * @throws IOException
   */
  public String OutputExcel() throws IOException {
    // excel表格名字
    String filedisplay = "未匹配的产品清单.xls";
    // excel标题
    String title = "POI测试";
    filedisplay = URLEncoder.encode(filedisplay, "UTF-8");

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/x-download");
    response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);

    ExportExcel<Student> ex = new ExportExcel<Student>();
    String[] headers = {"学号", "姓名", "年龄", "性别", "出生日期"};
    List<Student> dataset = new ArrayList<Student>();
    dataset.add(new Student(10000001, "张三", 20, "男", new Date()));
    dataset.add(new Student(20000002, "李四", 24, "女", new Date()));
    dataset.add(new Student(30000003, "王五", 22, "女", new Date()));

    // OutputStream out = new FileOutputStream("d://a.xls");
    OutputStream out = response.getOutputStream();
    ex.exportExcel(title, headers, dataset, out);
    out.close();
    // JOptionPane.showMessageDialog(null, "导出成功!");
    return null;
  }

  /**
   * 导入excel
   *
   * @throws IOException
   * @throws FileNotFoundException
   */
  public String InputExcel() throws FileNotFoundException, IOException {

    Student student = null;
    // String path = "C:\\Users\\user\\Desktop\\未匹配的产品清单.xls";// 文件路径
    try {
      // File files = new File(path);
      String[][] result = InputExcel.getData(excelFile, 1);

      if (result != null) {
        list = new ArrayList<Student>();

        int rowLength = result.length;
        Date date;
        for (int i = 0; i < rowLength; i++) {
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
          // for (int j = 0; j < result[i].length; j++) {

          // System.out.println(result[i][j] + "单元格ID:" + i + " "+ j);
          student = new Student();
          if (result[i][0] != null && !"".equals(result[i][0])) {
            student.setId(Integer.parseInt(result[i][0]));
          }
          if (result[i][1] != null && !"".equals(result[i][1])) {
            student.setName(result[i][1]);
          } else {
            student.setName("null");
          }
          if (result[i][2] != null && !"".equals(result[i][2])) {
            student.setAge(Integer.parseInt(result[i][2]));
          }
          if (result[i][3] != null && !"".equals(result[i][3])) {
            student.setSex(result[i][3]);
          } else {
            student.setSex("null");
          }
          if (result[i][4] != null && !"".equals(result[i][4])) {
            date = sdf.parse(result[i][4]);
            student.setBirthday(date);
          }

          list.add(student);
          // }
        }

        System.out.println(list.size());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return SUCCESS;
  }

  // 判断文件类型
  public Workbook createWorkBook(InputStream is) throws IOException {
    if (excelFileFileName.toLowerCase().endsWith("xls")) {
      return new HSSFWorkbook(is);
    }
    if (excelFileFileName.toLowerCase().endsWith("xlsx")) {
      return new XSSFWorkbook(is);
    }
    return null;
  }

  public File getExcelFile() {
    return excelFile;
  }

  public void setExcelFile(File excelFile) {
    this.excelFile = excelFile;
  }

  public String getExcelFileFileName() {
    return excelFileFileName;
  }

  public void setExcelFileFileName(String excelFileFileName) {
    this.excelFileFileName = excelFileFileName;
  }

  public ExcelWorkSheet<Student> getExcelWorkSheet() {
    return excelWorkSheet;
  }

  public void setExcelWorkSheet(ExcelWorkSheet<Student> excelWorkSheet) {
    this.excelWorkSheet = excelWorkSheet;
  }

  public List<Student> getList() {
    return list;
  }

  public void setList(List<Student> list) {
    this.list = list;
  }
}
  @SuppressWarnings("unchecked")
  public String execute() throws Exception {
    try {
      Context context = getContext();
      Context sessionContext = this.getSessionContext(); // sessio
      Map<String, Object> dataMap = sessionContext.getDataMap();
      String cstNo = (String) dataMap.get("cstNo"); // 客户号
      String cstName = (String) dataMap.get("userName"); // 客户名称

      Context parentContext = context.getParent();
      Map<String, Object> map = parentContext.getDataMap();
      String flowNo = (String) map.get("flowNo");

      context.put("flowNo", flowNo);
      context.put("cstNo", cstNo);
      context.put("channel", "302");

      context.put("receiveOrgno", URLMap.get("rcverId")); // 接收参与机构
      context.put("oldIBPSMsgId", URLMap.get("orgnlIBPSMsgId")); // 原报文标识号
      context.put("authenticationResult", "00"); // 认证结果00表示认证通过			99表示认证失败
      context.put("protocalNo", "0"); // 账户信息查询协议号 签署时填写0,撤销时填写正确的协议号
      context.put("custNo", URLMap.get("cstmrId")); // 客户号(第三方)
      context.put("payAccount", URLMap.get("payAcctNo")); // 付款人账号
      context.put("payAccountName", cstName); // 付款人户名
      context.put("paymentAccType", URLMap.get("payAcctType")); // 付款人账户类型01:借记卡;04:信用卡;05:对公账户
      context.put("payOpenBranchName", AppConstants.SELF_BANK_NAME); // 付款人开户行名称 (所属网银互联行名,常量)
      String fromDate = URLMap.get("fromDate"); // 生效日期
      String toDate = URLMap.get("toDate"); // 失效日期
      if ("".equals(fromDate)) {
        // 生效日期为空,默认当天生效
        fromDate = DateUtil.getServerTime("yyyyMMdd");
      }
      context.put("ptcFctvData", fromDate); // 协议生效日期
      context.put("ptcIfctvData", toDate); // 协议失效日期
      context.put("currency", "01"); // 币种
      context.put("singleQuota", URLMap.get("sigleLimit")); // 单笔金额上限
      context.put("dayBizNumQuota", URLMap.get("dayNumTop")); // 日累计业务笔数上限
      context.put("dayQuota", URLMap.get("dayLimit")); // 日累计金额上限
      context.put("monthBizNumQuota", URLMap.get("monthNumTop")); // 月累计业务笔数上限
      context.put("monthQuota", URLMap.get("monthLimit")); // 月累计金额上限
      context.put("remark", ""); // 备注

      context.put("randomNumber", URLMap.get("randomNumber")); // 随机数
      context.put("transTime", URLMap.get("transTime")); // 挑战码生成时间
      context.put("password", URLMap.get("password")); // 交易密码
      String safetool = URLMap.get("safetool");

      if ("3".equals(safetool)) {
        // 安全工具为令牌
        ActionContext acco = ActionContext.getContext();
        HttpServletRequest httpRequest = (HttpServletRequest) acco.get(HTTP_REQUEST);
        HttpSession cSession = httpRequest.getSession();
        context.put("safetool", safetool);
        context.put("tokenCode", URLMap.get("challengeCodeid"));
        context.put("custIdentiType", "1"); // 客户识别类型
        context.put("challengeCode", cSession.getAttribute("challengeCode"));
        context.put("transTime", URLMap.get("transTime"));
      } else if ("4".equals(safetool)) {
        context.put("safetool", safetool);
        context.put("singOrigInal", URLMap.get("singOrigInal")); // 签名原文
        context.put("singData", URLMap.get("signature")); // 签名后数据
      }

      IcopClientManager.callChannelService(context, "PSVR000067"); // 他行账户支付协议应答
    } catch (Exception e) {
      this.handleError(e);
      return ERROR;
    }
    return SUCCESS;
  }
  public String execute() throws Exception {
    int tempCol1 = 0;
    int tempRow1 = 1;

    System.out.println("Export to Excel");

    ActionContext ctx = ActionContext.getContext();
    HttpServletRequest req = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
    HttpSession session = req.getSession();
    BufferedImage chartImage = (BufferedImage) session.getAttribute("chartImage");
    PngEncoder encoder = new PngEncoder(chartImage, false, 0, 9);

    byte[] encoderBytes = encoder.pngEncode();
    Double[][] objData1 = (Double[][]) session.getAttribute("data1");
    Double[][] objData2 = (Double[][]) session.getAttribute("data2");

    String[] series1S = (String[]) session.getAttribute("series1");
    String[] series2S = (String[]) session.getAttribute("series2");
    String[] categories1S = (String[]) session.getAttribute("categories1");
    String[] categories2S = (String[]) session.getAttribute("categories2");

    initialzeAllLists(series1S, series2S, categories1S, categories2S);

    data1 = convertDoubleTodouble(objData1);
    data2 = convertDoubleTodouble(objData2);

    if (chartDisplayOption == null || chartDisplayOption.equalsIgnoreCase("none")) {
    } else if (chartDisplayOption.equalsIgnoreCase("ascend")) {
      sortByAscending();
    } else if (chartDisplayOption.equalsIgnoreCase("desend")) {
      sortByDesscending();
    } else if (chartDisplayOption.equalsIgnoreCase("alphabet")) {
      sortByAlphabet();
    }

    String outputReportFile =
        System.getenv("DHIS2_HOME") + File.separator + Configuration_IN.DEFAULT_TEMPFOLDER;
    File newdir = new File(outputReportFile);
    if (!newdir.exists()) {
      newdir.mkdirs();
    }
    outputReportFile += File.separator + UUID.randomUUID().toString() + ".xls";

    WritableWorkbook outputReportWorkbook = Workbook.createWorkbook(new File(outputReportFile));
    WritableSheet sheet0 = outputReportWorkbook.createSheet("ChartOutput", 0);

    if (viewSummary.equals("no")) {
      WritableImage writableImage = new WritableImage(0, 1, 10, 23, encoderBytes);
      sheet0.addImage(writableImage);
      tempRow1 = 24;
    } else {
      tempRow1 -= objData1.length;
    }

    int count1 = 0;
    int count2 = 0;
    int flag1 = 0;
    while (count1 <= categories1.length) {
      for (int j = 0; j < data1.length; j++) {
        tempCol1 = 1;
        tempRow1++;
        WritableCellFormat wCellformat1 = new WritableCellFormat();
        wCellformat1.setBorder(Border.ALL, BorderLineStyle.THIN);
        wCellformat1.setWrap(true);

        WritableCellFormat wCellformat2 = new WritableCellFormat();
        wCellformat2.setBorder(Border.ALL, BorderLineStyle.THIN);
        wCellformat2.setAlignment(Alignment.CENTRE);
        wCellformat2.setBackground(Colour.GRAY_25);
        wCellformat2.setWrap(true);

        WritableCell cell1;
        CellFormat cellFormat1;

        for (int k = count2; k < count1; k++) {
          if (k == count2 && j == 0) {
            tempCol1 = 0;
            tempRow1++;
            cell1 = sheet0.getWritableCell(tempCol1, tempRow1);
            cellFormat1 = cell1.getCellFormat();

            if (cell1.getType() == CellType.LABEL) {
              Label l = (Label) cell1;
              l.setString("Service");
              l.setCellFormat(cellFormat1);
            } else {
              sheet0.addCell(new Label(tempCol1, tempRow1, "Service", wCellformat2));
            }
            tempCol1++;

            for (int i = count2; i < count1; i++) {
              cell1 = sheet0.getWritableCell(tempCol1, tempRow1);
              cellFormat1 = cell1.getCellFormat();
              if (cell1.getType() == CellType.LABEL) {
                Label l = (Label) cell1;
                l.setString(categories1[i]);
                l.setCellFormat(cellFormat1);
              } else {
                sheet0.addCell(new Label(tempCol1, tempRow1, categories1[i], wCellformat2));
              }
              tempCol1++;
            }
            tempRow1++;
            tempCol1 = 1;
          }

          if (k == count2) {
            tempCol1 = 0;
            cell1 = sheet0.getWritableCell(tempCol1, tempRow1);
            cellFormat1 = cell1.getCellFormat();

            if (cell1.getType() == CellType.LABEL) {
              Label l = (Label) cell1;
              l.setString(series1[j]);
              l.setCellFormat(cellFormat1);
            } else {
              sheet0.addCell(new Label(tempCol1, tempRow1, series1[j], wCellformat2));
            }
            tempCol1++;
          }
          cell1 = sheet0.getWritableCell(tempCol1, tempRow1);
          cellFormat1 = cell1.getCellFormat();

          if (cell1.getType() == CellType.LABEL) {
            Label l = (Label) cell1;
            l.setString("" + data1[j][k]);
            l.setCellFormat(cellFormat1);
          } else {
            sheet0.addCell(new Number(tempCol1, tempRow1, data1[j][k], wCellformat1));
          }
          tempCol1++;
        }
      }
      if (flag1 == 1) break;
      count2 = count1;
      if ((count1 + 10 > categories1.length) && (categories1.length - count1 <= 10)) {
        count1 += categories1.length - count1;
        flag1 = 1;
      } else count1 += 10;
    }
    outputReportWorkbook.write();
    outputReportWorkbook.close();

    fileName = "chartOutput.xls";

    inputStream = new BufferedInputStream(new FileInputStream(outputReportFile));

    return SUCCESS;
  }
Example #30
0
 public String querylist() throws Exception {
   Qyyyrztj setQyyyrztj = new Qyyyrztj();
   setQyyyrztj = (Qyyyrztj) this.setClass(setQyyyrztj, null);
   Map map = new HashMap();
   map.put("dsjgdm", setQyyyrztj.getDsjgdm());
   map.put("fxjdm", setQyyyrztj.getFxjdm());
   map.put("gxdwdm", setQyyyrztj.getGxdwdm());
   map.put("dsjgbz", setQyyyrztj.getDsjgbz());
   map.put("fxjbz", setQyyyrztj.getFxjbz());
   map.put("gxdwbz", setQyyyrztj.getGxdwbz());
   map.put("hylbdm", setQyyyrztj.getHylbdm());
   map.put("qsrq", setQyyyrztj.getQsrq());
   map.put("jzrq", setQyyyrztj.getJzrq());
   ActionContext ctx = ActionContext.getContext();
   HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
   HttpSession session = request.getSession();
   User user = (User) session.getAttribute(Constants.userKey);
   String departTemp = user.getDepartment().getDepartcode();
   String DeptCode = departTemp;
   if (!setQyyyrztj.getDsjgdm().equals("")) DeptCode = setQyyyrztj.getDsjgdm();
   if (!setQyyyrztj.getFxjdm().equals("")) DeptCode = setQyyyrztj.getFxjdm();
   if (!setQyyyrztj.getGxdwdm().equals("")) DeptCode = setQyyyrztj.getGxdwdm();
   map.put("deptcode", StringUtil.trimEven0(DeptCode));
   if (DepartmentUtil.departIsZxs(departTemp)) map.put("iszxs", "1");
   Integer deptlevel = 2;
   if (!DepartmentUtil.departIsZxs(departTemp)) {
     if ("1".equals(setQyyyrztj.getGxdwbz())) {
       deptlevel = 5;
     } else if ("1".equals(setQyyyrztj.getFxjbz())) {
       deptlevel = 4;
     } else if ("1".equals(setQyyyrztj.getDsjgbz())) {
       deptlevel = 3;
     }
   } else {
     if ("1".equals(setQyyyrztj.getGxdwbz())) {
       deptlevel = 4;
     } else if ("1".equals(setQyyyrztj.getFxjbz())) {
       deptlevel = 3;
     } else if ("1".equals(setQyyyrztj.getDsjgbz())) {
       deptlevel = 2;
     }
   }
   map.put("deptlevel", deptlevel);
   Page page = qyyyrztjService.getListForPagetj(map, pagesize, pagerow, sort, dir);
   totalpage = page.getTotalPages();
   totalrows = page.getTotalRows();
   lQyyyrztj = page.getData();
   int qyzs = 0;
   int sccss = 0;
   int wsccss = 0;
   int cyrys = 0;
   int sbrs = 0;
   int xzrys = 0;
   int lzrys = 0;
   Qyyyrztj sumQyyyrztj = new Qyyyrztj();
   for (java.util.Iterator iter = lQyyyrztj.iterator(); iter.hasNext(); ) {
     Qyyyrztj oneQyyyrztj = (Qyyyrztj) iter.next();
     qyzs += oneQyyyrztj.getQyzs().intValue();
     sccss += oneQyyyrztj.getSccss().intValue();
     wsccss += oneQyyyrztj.getWsccss().intValue();
     cyrys += oneQyyyrztj.getCyrys().intValue();
     sbrs += oneQyyyrztj.getSbrs().intValue();
     xzrys += oneQyyyrztj.getXzrys().intValue();
     lzrys += oneQyyyrztj.getLzrys().intValue();
     if (oneQyyyrztj.getGxdwdm() != null && !oneQyyyrztj.getGxdwdm().equals("")) {
       oneQyyyrztj.setMxlj(
           "<a href='#' class='fontbutton' title='详细' onclick=setXxQuery('"
               + oneQyyyrztj.getGxdwdm()
               + "')>详细</a>");
     } else if (oneQyyyrztj.getFxjdm() != null && !oneQyyyrztj.getFxjdm().equals("")) {
       oneQyyyrztj.setMxlj(
           "<a href='#' class='fontbutton' title='详细' onclick=setXxQuery('"
               + oneQyyyrztj.getFxjdm()
               + "')>详细</a>");
     } else if (oneQyyyrztj.getDsjgdm() != null && !oneQyyyrztj.getDsjgdm().equals("")) {
       oneQyyyrztj.setMxlj(
           "<a href='#' class='fontbutton' title='详细' onclick=setXxQuery('"
               + oneQyyyrztj.getDsjgdm()
               + "')>详细</a>");
     }
   }
   sumQyyyrztj.setQyzs(qyzs);
   sumQyyyrztj.setSccss(sccss);
   sumQyyyrztj.setWsccss(wsccss);
   sumQyyyrztj.setCyrys(cyrys);
   sumQyyyrztj.setSbrs(sbrs);
   sumQyyyrztj.setXzrys(xzrys);
   sumQyyyrztj.setLzrys(lzrys);
   // sumQyyyrztj.setMxlj("");
   sumQyyyrztj.setDsjgmc("总计");
   if ("1".equals(setQyyyrztj.getDsjgbz())) {
     lQyyyrztj.add(sumQyyyrztj);
   }
   this.result = "success";
   return "success";
 }