コード例 #1
1
 @Override
 public StudentManagerDTO saveStudent(String name, String classId, String schoolId) {
   UserDTO userDTO = new UserDTO();
   userDTO.setRealName(name);
   userDTO.setIdentityId(IdentityIdConstants.STUDENT);
   userDTO.setIdentityDescription("学生");
   userDTO.setSchoolId(schoolId);
   userDTO.setArea(mSchoolMapper.selectByPrimaryKey(schoolId).getArea());
   UserDTO users = userService.saveUser(userDTO);
   MClass mclass = classMapper.selectByPrimaryKey(classId, schoolId);
   StudentDTO studentDTO = new StudentDTO();
   studentDTO.setUserId(users.getUserId());
   studentDTO.setSchoolId(mclass.getSchoolId());
   studentDTO.setSchoolName(mclass.getSchoolName());
   studentDTO.setClassName(mclass.getName());
   studentDTO.setClassId(classId);
   studentDTO.setClassAliasName(mclass.getAliasName());
   studentDTO.setJoinClass(new Date());
   MStudent mStudent = new MStudent();
   BeanUtils.copyProperties(studentDTO, mStudent);
   studentMapper.insert(mStudent);
   MStudentManager studentManager =
       studentMapper.selectStudentByUserId(mStudent.getUserId(), schoolId);
   StudentManagerDTO studentManagerDTO = new StudentManagerDTO();
   BeanUtils.copyProperties(studentManager, studentManagerDTO);
   studentManagerDTO.setClassAliasName(
       ClassNameUtil.getFullName(studentManager.getYears(), studentManager.getClassAliasName()));
   return studentManagerDTO;
 }
コード例 #2
0
  @Transactional(propagation = Propagation.SUPPORTS)
  public boolean hasAccessToDevice(AccessKey accessKey, String deviceGuid) {
    Set<AccessKeyPermission> permissions = accessKey.getPermissions();
    Set<String> allowedDevices = new HashSet<>();
    Set<Long> allowedNetworks = new HashSet<>();

    User accessKeyUser = userService.findUserWithNetworks(accessKey.getUser().getId());
    Set<AccessKeyPermission> toRemove = new HashSet<>();

    Device device =
        genericDAO
            .createNamedQuery(Device.class, "Device.findByUUID", of(CacheConfig.refresh()))
            .setParameter("guid", deviceGuid)
            .getSingleResult();

    for (AccessKeyPermission currentPermission : permissions) {
      if (currentPermission.getDeviceGuidsAsSet() == null) {
        allowedDevices.add(null);
      } else {
        if (!currentPermission.getDeviceGuidsAsSet().contains(deviceGuid)) {
          toRemove.add(currentPermission);
        } else {
          allowedDevices.addAll(currentPermission.getDeviceGuidsAsSet());
        }
      }
      if (currentPermission.getNetworkIdsAsSet() == null) {
        allowedNetworks.add(null);
      } else {
        if (device.getNetwork() != null) {
          if (!currentPermission.getNetworkIdsAsSet().contains(device.getNetwork().getId())) {
            toRemove.add(currentPermission);
          } else {
            allowedNetworks.addAll(currentPermission.getNetworkIdsAsSet());
          }
        }
      }
    }
    permissions.removeAll(toRemove);
    boolean hasAccess;
    hasAccess =
        allowedDevices.contains(null)
            ? userService.hasAccessToDevice(accessKeyUser, device.getGuid())
            : allowedDevices.contains(device.getGuid())
                && userService.hasAccessToDevice(accessKeyUser, device.getGuid());

    hasAccess =
        hasAccess && allowedNetworks.contains(null)
            ? accessKeyUser.isAdmin() || accessKeyUser.getNetworks().contains(device.getNetwork())
            : (accessKeyUser.isAdmin() || accessKeyUser.getNetworks().contains(device.getNetwork()))
                && allowedNetworks.contains(device.getNetwork().getId());

    return hasAccess;
  }
  /**
   * Process the specified HTTP request, and create the corresponding HTTP response (or forward to
   * another web component that will create it). Return an <code>ActionForward</code> instance
   * describing where and how control should be forwarded, or <code>null</code> if the response has
   * already been completed.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @exception Exception if business logic throws an exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // Extract attributes we will need
    MessageResources messages = getResources(request);

    // save errors
    ActionMessages errors = new ActionMessages();

    // START check for login (security)
    if (!SecurityService.getInstance().checkForLogin(request.getSession(false))) {
      return (mapping.findForward("welcome"));
    }
    // END check for login (security)

    // PRIVS check that hrAdmin user is viewing this page
    if (!StandardCode.getInstance()
        .checkPrivStringArray(
            (String[]) request.getSession(false).getAttribute("userPrivs"), "hrAdmin")) {
      return (mapping.findForward("accessDenied"));
    } // END PRIVS check that hrAdmin user is viewing this page

    // get the employee to edit from the request
    String hrAdminUserId = request.getParameter("hrAdminUserId");
    User u = UserService.getInstance().getSingleUser(Integer.valueOf(hrAdminUserId));

    // get new performance review values
    DynaValidatorForm ha = (DynaValidatorForm) form;
    String dueDate = (String) ha.get("dueDate");
    String actualDate = (String) ha.get("actualDate");
    String signedDate = (String) ha.get("signedDate");
    PerformanceReview performanceReviewNew = (PerformanceReview) ha.get("performanceReviewNew");

    if (dueDate.length() > 0) // if entered
    performanceReviewNew.setDueDate(DateService.getInstance().convertDate(dueDate).getTime());
    if (actualDate.length() > 0) // if entered
    performanceReviewNew.setActualDate(DateService.getInstance().convertDate(actualDate).getTime());
    if (signedDate.length() > 0) // if entered
    performanceReviewNew.setSignedDate(DateService.getInstance().convertDate(signedDate).getTime());

    // add new performanceReview to the db
    UserService.getInstance().addPerformanceReview(performanceReviewNew, u);

    // Forward control to the specified success URI
    return (mapping.findForward("Success"));
  }
コード例 #4
0
  @Override
  public SearchResultWrapper<Test> getAvailableTests() {
    TestSearchTO search = new TestSearchTO();
    search.setGroupFilter(GroupFilter.MY_GROUPS);
    List<String> groups = userService.getLoggedUserGroupNames();

    return testDAO.searchTests(search, groups);
  }
コード例 #5
0
 @Transactional(propagation = Propagation.SUPPORTS)
 public boolean hasAccessToNetwork(AccessKey accessKey, Network targetNetwork) {
   Set<AccessKeyPermission> permissions = accessKey.getPermissions();
   User user = accessKey.getUser();
   boolean hasNullPermission =
       permissions.stream().anyMatch(perm -> perm.getNetworkIdsAsSet() == null);
   if (hasNullPermission) {
     return userService.hasAccessToNetwork(user, targetNetwork);
   } else {
     Set<Long> allowedNetworks =
         permissions
             .stream()
             .map(AccessKeyPermission::getNetworkIdsAsSet)
             .flatMap(Collection::stream)
             .collect(Collectors.toSet());
     user = userService.findUserWithNetworks(user.getId());
     return allowedNetworks.contains(targetNetwork.getId())
         && (user.isAdmin() || user.getNetworks().contains(targetNetwork));
   }
 }
コード例 #6
0
 @Override
 public Test createTest(Test test) throws ServiceException {
   if (!userService.isLoggedUserInGroup(test.getGroupId())) {
     throw new org.perfrepo.web.security.SecurityException(
         "securityException.userNotInGroup.createTest",
         userService.getLoggedUser().getUsername(),
         test.getGroupId());
   }
   if (testDAO.findByUid(test.getUid()) != null) {
     throw new ServiceException("serviceException.testUidExists", test.getUid());
   }
   Test createdTest = testDAO.create(test);
   // store metrics
   if (test.getMetrics() != null) {
     for (Metric metric : test.getMetrics()) {
       addMetric(test, metric);
     }
   }
   return createdTest;
 }
コード例 #7
0
 @Override
 public List<String> getTestsByPrefix(String prefix) {
   List<Test> tests = testDAO.findByUIDPrefix(prefix);
   List<String> testuids = new ArrayList<String>();
   for (Test test : tests) {
     if (userService.isLoggedUserInGroup(test.getGroupId())) {
       testuids.add(test.getUid());
     }
   }
   return testuids;
 }
コード例 #8
0
 /** 导出学生信息 */
 @Override
 public List<ExcelInfo> queryExcelInfo(StudentPageRequest studentPageRequest) {
   Map<Integer, ExcelInfo> map = new TreeMap<>();
   String schoolId = studentPageRequest.getSchoolId();
   if (schoolId == null) {
     schoolId = userService.getSchoolId(studentPageRequest.getUserId());
     studentPageRequest.setSchoolId(schoolId);
   }
   // 获取学生信息的总条数
   MStudentManager studentManager = new MStudentManager();
   BeanUtils.copyProperties(studentPageRequest, studentManager);
   List<MStudentManager> mStudentList = studentMapper.selectStudents_export(studentManager);
   for (MStudentManager students : mStudentList) {
     List<List<Object>> data;
     List<Object> row = new ArrayList<>();
     row.add(students.getRealName());
     if (students.getYears() != null) {
       int grade = ClassNameUtil.getGradeNum(students.getYears());
       ExcelInfo excelInfo = map.get(grade);
       if (excelInfo == null) {
         excelInfo = new ExcelInfo();
         data = new ArrayList<>();
         excelInfo.setData(data);
         excelInfo.setSheetName(grade + "年级");
         excelInfo.setHeaders(new String[] {"学生姓名", "所在班级", "登录账号", "上线情况"});
         excelInfo.setColumnWidth(20);
         map.put(grade, excelInfo);
       } else {
         data = excelInfo.getData();
       }
       row.add(grade + "年级" + students.getClassAliasName());
     } else {
       ExcelInfo excelInfo = map.get(0);
       if (excelInfo == null) {
         excelInfo = new ExcelInfo();
         data = new ArrayList<>();
         excelInfo.setData(data);
         excelInfo.setSheetName("无班级");
         excelInfo.setColumnWidth(20);
         excelInfo.setHeaders(new String[] {"学生姓名", "所在班级", "登录账号", "上线情况"});
         map.put(0, excelInfo);
       } else {
         data = excelInfo.getData();
       }
       row.add("无班级");
     }
     row.add(students.getUserId());
     row.add(DateUtil.getLogin_date(students.getLastLoginDate()));
     data.add(row);
   }
   return new ArrayList<>(map.values());
 }
コード例 #9
0
 /** 根据学生ID获取学生信息 */
 @Override
 public MyMessageDTO getMyMessageStudent(String userId) {
   String schoolId = userService.getSchoolId(userId);
   MStudentInfo studentInfo = studentMapper.getStudentInfo(userId, schoolId);
   if (studentInfo == null) {
     throw new MemberException("该学生不存在");
   }
   MyMessageDTO studentInfoDTO = new MyMessageDTO();
   BeanUtils.copyProperties(studentInfo, studentInfoDTO);
   if (studentInfo.getClassId() != null) {
     studentInfoDTO.setClassName(
         ClassNameUtil.getFullName(studentInfo.getYear(), studentInfo.getClassName()));
   }
   return studentInfoDTO;
 }
コード例 #10
0
  @Override
  public SearchResultWrapper<TestExecution> searchTestExecutions(TestExecutionSearchTO search) {
    // remove param criteria with empty param name
    if (search.getParameters() != null) {
      for (Iterator<ParamCriteria> allParams = search.getParameters().iterator();
          allParams.hasNext(); ) {
        ParamCriteria param = allParams.next();
        if (param.isNameEmpty()) {
          allParams.remove();
        }
      }
    }

    return testExecutionDAO.searchTestExecutions(search, userService.getLoggedUserGroupNames());
  }
コード例 #11
0
 /** APP接口、WEB平台:根据学生名称查询学生信息 */
 @Override
 public List<StudentManagerDTO> queryStudentByRealName(String realName, String userId) {
   if (StringUtils.isEmpty(userId)) {
     logger.debug("userId 不能为空");
     return null;
   }
   String schoolId = userService.getSchoolId(userId);
   List<MStudentManager> userList = studentMapper.selectStudentByRealName(realName, schoolId);
   List<StudentManagerDTO> userDTOList = new ArrayList<>();
   for (MStudentManager u : userList) {
     StudentManagerDTO userDTO = new StudentManagerDTO();
     BeanUtils.copyProperties(u, userDTO);
     userDTOList.add(userDTO);
   }
   return userDTOList;
 }
コード例 #12
0
  @Transactional(propagation = Propagation.REQUIRED)
  public AccessKey authenticate(@NotNull User user) {
    userService.refreshUserLoginData(user);

    AccessKey accessKey = authenticationUtils.prepareAccessKey(user);

    Set<AccessKeyPermission> permissions = new HashSet<>();
    final AccessKeyPermission permission = authenticationUtils.preparePermission(user.getRole());
    permissions.add(permission);
    accessKey.setPermissions(permissions);
    genericDAO.persist(accessKey);

    permission.setAccessKey(accessKey);
    genericDAO.persist(permission);
    return accessKey;
  }
コード例 #13
0
 /** APP接口:根据学生ID获取该学生所在的班级信息 */
 @Override
 public ClassInfoDTO queryUserClass(String userId) {
   String schoolId = userService.getSchoolId(userId);
   MClassInfo studentClass = studentMapper.getStudentClass(userId, schoolId);
   ClassInfoDTO tcdto = new ClassInfoDTO();
   if (studentClass != null) {
     BeanUtils.copyProperties(studentClass, tcdto);
     // 设置年级号
     tcdto.setGradeNum(ClassNameUtil.getGradeNum(studentClass.getYear()));
     // 设置学期
     tcdto.setSemester(ClassNameUtil.getSemester());
     // 设置班级名称 年级+班级
     tcdto.setClassName(
         ClassNameUtil.getFullName(studentClass.getYear(), studentClass.getClassName()));
   }
   return tcdto;
 }
コード例 #14
0
 /** 通知用 根据学生Id查询家庭成员 */
 @Override
 public List<FamilyRelationDTO> queryFamilyByStudent(String userId) {
   String key = MessageFormat.format(CacheConstants.KEY_PARENT_OF_KID, userId);
   List<FamilyRelationDTO> list = cacheService.get(key);
   if (list != null) {
     return list;
   }
   List<FamilyRelationDTO> familyRelationDTOs = new ArrayList<>();
   List<MFamilyRelation> mFamilyRelations =
       famillyRelationMapper.queryFamilyByStudent(userId, userService.getSchoolId(userId));
   for (MFamilyRelation fr : mFamilyRelations) {
     FamilyRelationDTO familyRelationDTO = new FamilyRelationDTO();
     BeanUtils.copyProperties(fr, familyRelationDTO);
     familyRelationDTOs.add(familyRelationDTO);
   }
   cacheService.set(key, familyRelationDTOs, CacheConstants.CACHE_SEVEN_DAY, TimeUnit.DAYS);
   return familyRelationDTOs;
 }
コード例 #15
0
  /**
   * Process the specified HTTP request, and create the corresponding HTTP response (or forward to
   * another web component that will create it). Return an <code>ActionForward</code> instance
   * describing where and how control should be forwarded, or <code>null</code> if the response has
   * already been completed.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @exception Exception if business logic throws an exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // Extract attributes we will need
    MessageResources messages = getResources(request);

    // save errors
    ActionMessages errors = new ActionMessages();

    // START check for login (security)
    if (!SecurityService.getInstance().checkForLogin(request.getSession(false))) {
      return (mapping.findForward("welcome"));
    }
    // END check for login (security)

    // get the current user for displaying personal info, such as "My Projects"
    User u =
        UserService.getInstance()
            .getSingleUser((String) request.getSession(false).getAttribute("username"));
    System.out.println(
        "local addresss sssssssssssssss"
            + request.getLocalAddr()
            + "          "
            + request.getLocalName());
    long startProjects = System.currentTimeMillis();
    String myName = u.getFirstName() + " " + u.getLastName();
    List myHr = HrHelper.getAllEmployeesFormer(u);
    long endProjects = System.currentTimeMillis();
    System.out.println("GetMyHrAction took:" + ((endProjects - startProjects) / 1000.0));
    response.setContentType("text/html");
    response.setHeader("Cache-Control", "no-cache");
    // System.out.println(actResponse.toXML());
    PrintWriter out = response.getWriter();
    out.println(new JSONArray(myHr.toArray()));
    out.flush();

    // Forward control to the specified success URI
    return (null);
  }
コード例 #16
0
  @Override
  public StudentDTO queryStudentForAPP(String userId, String schoolId) {
    UserDTO mUsers = userService.getByUserId(userId);
    if (mUsers == null) {
      logger.debug("未找到学乐号为" + userId + "的学生用户");
      return null;
    }

    MStudent mStudent = studentMapper.selectByPrimaryKey(userId, schoolId);
    if (mStudent == null) {
      logger.debug("未找到学生id为" + userId + "的学生");
      throw new MemberException("未找到学生id为" + userId + "的学生");
    }
    // 学生信息
    StudentDTO studentDTO = new StudentDTO();
    studentDTO.setUserId(userId);
    studentDTO.setRealName(mUsers.getRealName());
    studentDTO.setSchoolId(mStudent.getSchoolId());
    studentDTO.setSchoolName(mStudent.getSchoolName());
    studentDTO.setClassId(mStudent.getClassId());
    studentDTO.setClassName(mStudent.getClassName());
    studentDTO.setMobile(mUsers.getMobile());
    studentDTO.setEmail(mUsers.getEmail());

    // 学校所在区域信息
    MSchool mSchool = mSchoolMapper.selectByPrimaryKey(mUsers.getSchoolId());
    if (mSchool == null) {
      logger.debug("未找到学乐号为" + userId + "的学生用户所在的学校");
      return null;
    }
    studentDTO.setAreaCode(mSchool.getArea());
    studentDTO.setAreaName(mSchool.getAreaName());

    // 班级信息
    MClass mClass = classMapper.selectByPrimaryKey(mStudent.getClassId(), schoolId);
    if (mClass == null) {
      logger.debug("未找到学乐号为" + userId + "的学生用户所在的班级");
      return null;
    }
    studentDTO.setGradeNum(getGradeNum(mClass.getYears()));
    studentDTO.setYear(mClass.getYears());
    return studentDTO;
  }
コード例 #17
0
  /** 查询学生信息分页 */
  @Override
  public PageResponse<StudentManagerDTO> queryStudentPage(StudentPageRequest studentPageRequest) {
    String schoolId = studentPageRequest.getSchoolId();
    if (schoolId == null) {
      schoolId = userService.getSchoolId(studentPageRequest.getUserId());
      studentPageRequest.setSchoolId(schoolId);
    }
    // 获取学生信息的总条数
    MStudentManager studentManager = new MStudentManager();
    BeanUtils.copyProperties(studentPageRequest, studentManager);
    long count = studentMapper.selectCount(studentManager);
    // 获取当前页的信息
    Page page = PageUtils.buildPage(studentPageRequest);
    List<MStudentManager> mStudentList =
        studentMapper.selectMStudentManagerPage(page, studentManager);
    /*
    给返回接口赋值
     */
    List<StudentManagerDTO> studentManagerDTOs = new ArrayList<>();
    for (MStudentManager mstudents : mStudentList) {
      StudentManagerDTO studentManagerDTO = new StudentManagerDTO();
      BeanUtils.copyProperties(mstudents, studentManagerDTO);
      studentManagerDTO.setLastLoginDate(
          mstudents.getLastLoginDate() == null
              ? "从未登录"
              : DateFormatUtils.format(mstudents.getLastLoginDate(), "yyyy-MM-dd HH:mm"));
      if (mstudents.getYears() != null) {
        studentManagerDTO.setClassAliasName(
            getGrade(mstudents.getYears()) + studentManagerDTO.getClassAliasName());
      } else {
        studentManagerDTO.setClassAliasName("无班级");
      }
      studentManagerDTOs.add(studentManagerDTO);
    }

    // 返回对象
    PageResponse<StudentManagerDTO> pageResponse = new PageResponse<>();
    PageUtils.buldPageResponse(studentPageRequest, pageResponse);
    pageResponse.setRows(studentManagerDTOs);
    pageResponse.setRecords(count);
    return pageResponse;
  }
コード例 #18
0
 /** 修改学生信息 */
 @Override
 public StudentManagerDTO updateStudentInfo(String userId, String realName, String classId) {
   String schoolId = userService.getSchoolId(userId);
   // 更换用户名称
   usersMapper.updateUserName(userId, realName, schoolId);
   // 更换班级
   MClass mClass = classMapper.selectByPrimaryKey(classId, schoolId);
   studentMapper.updateStudentMessage(userId, mClass);
   // 修改家庭关系表中用户名称
   familyRelationService.updateName(userId, realName);
   MStudentManager studentManager = studentMapper.selectStudentByUserId(userId, schoolId);
   StudentManagerDTO studentManagerDTO = new StudentManagerDTO();
   BeanUtils.copyProperties(studentManager, studentManagerDTO);
   studentManagerDTO.setClassAliasName(
       getGrade(mClass.getYears()) + studentManagerDTO.getClassAliasName());
   // 修改孩子名称,班级信息,删除缓存数据
   deleteRedisOfParent(userId, schoolId);
   cacheService.delete(MessageFormat.format(CacheConstants.KEY_USER, userId));
   return studentManagerDTO;
 }
コード例 #19
0
  @Override
  public StudentDTO updateStudentForAPP(StudentDTO studentDTO) {
    // 更新联系方式
    UserDTO userDTO = new UserDTO();
    boolean isAllNot = true;
    // 学生姓名
    String name = studentDTO.getRealName();
    if (!StringUtils.isEmpty(name)) {
      userDTO.setRealName(name);
      isAllNot = false;
    }

    String school = studentDTO.getSchoolId();
    if (school != null) {
      userDTO.setSchoolId(school);
      isAllNot = false;
    } else {
      logger.warn("schoolId不能为空");
      return null;
    }

    String userId = studentDTO.getUserId();
    if (!StringUtils.isEmpty(userId)) {
      userDTO.setUserId(userId);
    } else {
      logger.warn("userId不能为空");
      return null;
    }

    String mobile = studentDTO.getMobile();
    if (!StringUtils.isEmpty(mobile)) {
      userDTO.setMobile(mobile);
      isAllNot = false;
    }

    String email = studentDTO.getEmail();
    if (!StringUtils.isEmpty(email)) {
      userDTO.setEmail(email);
      isAllNot = false;
    }

    if (!isAllNot) {
      userService.updateByUserId(userDTO);
    }

    // 更新班级
    String schoolId = userService.getSchoolId(userId);
    if (StringUtils.isEmpty(schoolId)) {
      throw new MemberException("该学生没有学校");
    }

    MSchool mSchool = mSchoolMapper.selectByPrimaryKey(schoolId);

    String classId = studentDTO.getClassId();
    if (!StringUtils.isEmpty(classId)) {
      MClass mClass = classMapper.selectByPrimaryKey(classId, schoolId);
      if (mClass == null) {
        logger.warn("找不到班级号为" + classId + "的班级");
        return null;
      }
      MStudent mStudent = new MStudent();
      mStudent.setUserId(studentDTO.getUserId());
      mStudent.setClassName(mClass.getName());
      mStudent.setClassId(classId);
      mStudent.setSchoolId(schoolId);

      studentMapper.updateByPrimaryKey(mStudent);
    }

    studentDTO.setClassId(classId);
    studentDTO.setSchoolId(schoolId);
    studentDTO.setSchoolName(mSchool.getName());
    return studentDTO;
  }
コード例 #20
0
 @Override
 public SearchResultWrapper<Test> searchTest(TestSearchTO search) {
   return testDAO.searchTests(search, userService.getLoggedUserGroupNames());
 }
コード例 #21
0
  /**
   * Process the specified HTTP request, and create the corresponding HTTP response (or forward to
   * another web component that will create it). Return an <code>ActionForward</code> instance
   * describing where and how control should be forwarded, or <code>null</code> if the response has
   * already been completed.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @exception Exception if business logic throws an exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // Extract attributes we will need
    MessageResources messages = getResources(request);

    // save errors
    ActionMessages errors = new ActionMessages();

    // START check for login (security)
    if (!SecurityService.getInstance().checkForLogin(request.getSession(false))) {
      return (mapping.findForward("welcome"));
    }
    // END check for login (security)

    // START get id of current project from either request, attribute, or cookie
    // id of project from request
    String projectId = null;
    projectId = request.getParameter("projectViewId");

    // check attribute in request
    if (projectId == null) {
      projectId = (String) request.getAttribute("projectViewId");
    }

    // id of project from cookie
    if (projectId == null) {
      projectId = StandardCode.getInstance().getCookie("projectViewId", request.getCookies());
    }

    // default project to last if not in request or cookie
    if (projectId == null) {
      java.util.List results = ProjectService.getInstance().getProjectList();

      ListIterator iterScroll = null;
      for (iterScroll = results.listIterator(); iterScroll.hasNext(); iterScroll.next()) {}
      iterScroll.previous();
      Project p = (Project) iterScroll.next();
      projectId = String.valueOf(p.getProjectId());
    }

    Integer id = Integer.valueOf(projectId);

    // END get id of current project from either request, attribute, or cookie

    // get project
    Project p = ProjectService.getInstance().getSingleProject(id);

    // get user (project manager)
    User u =
        UserService.getInstance()
            .getSingleUserRealName(
                StandardCode.getInstance().getFirstName(p.getPm()),
                StandardCode.getInstance().getLastName(p.getPm()));

    // START process pdf
    try {
      PdfReader reader = new PdfReader("C://templates/CL01_001.pdf"); // the template

      // save the pdf in memory
      ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();

      // the filled-in pdf
      PdfStamper stamp = new PdfStamper(reader, pdfStream);

      // stamp.setEncryption(true, "pass", "pass", PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
      AcroFields form1 = stamp.getAcroFields();
      Date cDate = new Date();
      Integer month = cDate.getMonth();
      Integer day = cDate.getDate();
      Integer year = cDate.getYear() + 1900;
      String[] monthName = {
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
      };

      // set the field values in the pdf form
      // form1.setField("", projectId)
      form1.setField("currentdate", monthName[month] + " " + day + ", " + year);
      form1.setField(
          "firstname", StandardCode.getInstance().noNull(p.getContact().getFirst_name()));
      form1.setField("pm", p.getPm());
      form1.setField("emailpm", u.getWorkEmail1());
      if (u.getWorkPhoneEx() != null && u.getWorkPhoneEx().length() > 0) { // ext present
        form1.setField(
            "phonepm",
            StandardCode.getInstance().noNull(u.getWorkPhone())
                + " ext "
                + StandardCode.getInstance().noNull(u.getWorkPhoneEx()));
      } else { // no ext present
        form1.setField("phonepm", StandardCode.getInstance().noNull(u.getWorkPhone()));
      }
      form1.setField("faxpm", StandardCode.getInstance().noNull(u.getLocation().getFax_number()));
      form1.setField("postalpm", StandardCode.getInstance().printLocation(u.getLocation()));

      // START add images
      //                if(u.getPicture() != null && u.getPicture().length() > 0) {
      //                    PdfContentByte over;
      //                    Image img = Image.getInstance("C:/Program Files (x86)/Apache Software
      // Foundation/Tomcat 7.0/webapps/logo/images/" + u.getPicture());
      //                    img.setAbsolutePosition(200, 200);
      //                    over = stamp.getOverContent(1);
      //                    over.addImage(img, 54, 0,0, 65, 47, 493);
      //                }
      // END add images
      form1.setField("productname", StandardCode.getInstance().noNull(p.getProduct()));
      form1.setField("project", p.getNumber() + p.getCompany().getCompany_code());
      form1.setField("description", StandardCode.getInstance().noNull(p.getProductDescription()));
      form1.setField("additional", p.getProjectRequirements());

      // get sources and targets
      StringBuffer sources = new StringBuffer("");
      StringBuffer targets = new StringBuffer("");
      if (p.getSourceDocs() != null) {
        for (Iterator iterSource = p.getSourceDocs().iterator(); iterSource.hasNext(); ) {
          SourceDoc sd = (SourceDoc) iterSource.next();
          sources.append(sd.getLanguage() + " ");
          if (sd.getTargetDocs() != null) {
            for (Iterator iterTarget = sd.getTargetDocs().iterator(); iterTarget.hasNext(); ) {
              TargetDoc td = (TargetDoc) iterTarget.next();
              if (!td.getLanguage().equals("All")) targets.append(td.getLanguage() + " ");
            }
          }
        }
      }

      form1.setField("source", sources.toString());
      form1.setField("target", targets.toString());
      form1.setField(
          "start",
          (p.getStartDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getStartDate())
              : "");
      form1.setField(
          "due",
          (p.getDueDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getDueDate())
              : "");

      if (p.getCompany().getCcurrency().equalsIgnoreCase("USD")) {

        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "$ " + StandardCode.getInstance().formatDouble(p.getProjectAmount())
                : "");
      } else {
        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "€ "
                    + StandardCode.getInstance()
                        .formatDouble(p.getProjectAmount() / p.getEuroToUsdExchangeRate())
                : "");
      }
      // stamp.setFormFlattening(true);
      stamp.close();

      // write to client (web browser)

      response.setHeader(
          "Content-disposition",
          "attachment; filename="
              + p.getNumber()
              + p.getCompany().getCompany_code()
              + "-Order-Confirmation"
              + ".pdf");

      OutputStream os = response.getOutputStream();
      pdfStream.writeTo(os);
      os.flush();
    } catch (Exception e) {
      System.err.println("PDF Exception:" + e.getMessage());
      throw new RuntimeException(e);
    }
    // END process pdf

    // Forward control to the specified success URI
    return (mapping.findForward("Success"));
  }
コード例 #22
0
  public String execute() throws Exception {
    UserCredentials currentUserCredentials =
        currentUserService.getCurrentUser() != null
            ? currentUserService.getCurrentUser().getUserCredentials()
            : null;

    // ---------------------------------------------------------------------
    // Prepare values
    // ---------------------------------------------------------------------

    if (email != null && email.trim().length() == 0) {
      email = null;
    }

    if (rawPassword != null && rawPassword.trim().length() == 0) {
      rawPassword = null;
    }

    // ---------------------------------------------------------------------
    // Update userCredentials and user
    // ---------------------------------------------------------------------

    Collection<OrganisationUnit> units =
        selectionTreeManager.getReloadedSelectedOrganisationUnits();

    User user = userService.getUser(id);
    user.setSurname(surname);
    user.setFirstName(firstName);
    user.setEmail(email);
    user.setPhoneNumber(phoneNumber);
    user.updateOrganisationUnits(new HashSet<OrganisationUnit>(units));

    UserCredentials userCredentials = userService.getUserCredentials(user);

    Set<UserAuthorityGroup> userAuthorityGroups = new HashSet<UserAuthorityGroup>();

    for (String id : selectedList) {
      UserAuthorityGroup group = userService.getUserAuthorityGroup(Integer.parseInt(id));

      if (currentUserCredentials != null && currentUserCredentials.canIssue(group)) {
        userAuthorityGroups.add(group);
      }
    }

    userCredentials.setUserAuthorityGroups(userAuthorityGroups);

    if (rawPassword != null) {
      userCredentials.setPassword(
          passwordManager.encodePassword(userCredentials.getUsername(), rawPassword));
    }

    if (jsonAttributeValues != null) {
      AttributeUtils.updateAttributeValuesFromJson(
          user.getAttributeValues(), jsonAttributeValues, attributeService);
    }

    userService.updateUserCredentials(userCredentials);
    userService.updateUser(user);

    if (currentUserService.getCurrentUser() == user) {
      selectionManager.setRootOrganisationUnits(units);
      selectionManager.setSelectedOrganisationUnits(units);

      selectionTreeManager.setRootOrganisationUnits(units);
      selectionTreeManager.setSelectedOrganisationUnits(units);
    }

    if (units.size() > 0) {
      selectionManager.setSelectedOrganisationUnits(units);
    }

    return SUCCESS;
  }
コード例 #23
0
ファイル: UserServlet.java プロジェクト: sorako/kotemaru
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    UserService userService = UserServiceFactory.getUserService();
    String retUrl = req.getParameter("url");
    if (retUrl == null) retUrl = "/";

    String pathInfo = req.getPathInfo();
    if (pathInfo.equals("/current")) {
      User user = userService.getCurrentUser();
      if (user == null) {
        res.setStatus(401);
        res.setContentType("text/plain; charset=utf-8");
        res.getWriter().write("Not login");
        return;
      }

      UserBean ub = getByEmail(user.getEmail());

      res.setContentType("application/json; charset=utf-8");
      res.setHeader("Cache-control", "no-cache");
      res.getWriter().write("{\"email\":\"" + user.getEmail() + "\"");
      if (ub != null) {
        res.getWriter().write(",\"nickName\":\"" + ub.getNickName() + "\"");
        res.getWriter().write(",\"isRegister\":true");
      } else {
        String nn = user.getNickname();
        if (nn == null) nn = user.getEmail();
        res.getWriter().write(",\"nickName\":\"" + nn + "\"");
        res.getWriter().write(",\"isRegister\":false");
      }
      res.getWriter().write("}");

    } else if (pathInfo.equals("/login")) {
      String url = userService.createLoginURL(retUrl);
      res.sendRedirect(url);
    } else if (pathInfo.equals("/logout")) {
      String url = userService.createLogoutURL(retUrl);
      res.sendRedirect(url);
    } else if (pathInfo.equals("/register")) {
      User user = userService.getCurrentUser();
      if (user == null) {
        res.setStatus(401);
        res.setContentType("text/plain; charset=utf-8");
        res.getWriter().write("Not login");
        return;
      }

      String nickName = req.getParameter("nickName");
      UserBean ub = getByNeckName(nickName);
      if (ub != null) {
        res.setStatus(403);
        res.setContentType("text/plain; charset=utf-8");
        res.getWriter().write("ニックネーム(" + nickName + ")は既に使われています。");
        return;
      }

      ub = new UserBean();
      ub.setEmail(user.getEmail());
      ub.setNickName(nickName);
      usbs.put(user.getEmail(), ub);
      ursbs.put(nickName, ub);

      FileBean fb = new FileBean();
      fb.setParentName("");
      fb.setLastName(nickName);
      fb.setDirectory(true);
      fb.setLastModified(System.currentTimeMillis());
      fb.setOwner(user.getEmail());
      fb.setNickName(nickName);
      sbs.put("/" + nickName, fb);

      res.sendRedirect(retUrl);
    }
  }