/** @see se.idega.idegaweb.commune.school.report.business.ReportModel#buildRowHeaders() */
  protected Header[] buildRowHeaders() {
    Header[] headers = null;

    try {
      ReportBusiness rb = getReportBusiness();
      Collection areas = rb.getElementarySchoolAreas();
      headers = new Header[areas.size() + 1];
      Iterator areaIter = areas.iterator();
      int headerIndex = 0;
      while (areaIter.hasNext()) {
        SchoolArea area = (SchoolArea) areaIter.next();
        Collection schools = getReportBusiness().getElementarySchools(area);
        headers[headerIndex] =
            new Header(
                area.getName(), Header.HEADERTYPE_ROW_NONLOCALIZED_HEADER, schools.size() + 1);
        Iterator schoolIter = schools.iterator();
        int childIndex = 0;
        while (schoolIter.hasNext()) {
          School school = (School) schoolIter.next();
          Header child = new Header(school.getName(), Header.HEADERTYPE_ROW_NONLOCALIZED_NORMAL);
          headers[headerIndex].setChild(childIndex, child);
          childIndex++;
        }
        Header header = new Header(KEY_SUM, Header.HEADERTYPE_ROW_SUM);
        headers[headerIndex].setChild(childIndex, header);
        headerIndex++;
      }
      Header header = new Header(KEY_TOTAL, Header.HEADERTYPE_ROW_TOTAL);
      headers[headerIndex] = header;
    } catch (RemoteException e) {
      log(e.getMessage());
    }

    return headers;
  }
  private String getSchoolName(User user) {
    try {
      SchoolUserHome home = (SchoolUserHome) IDOLookup.getHome(SchoolUser.class);
      SchoolUser schoolUser = home.findForUser(user);
      int schoolid = schoolUser.getSchoolId();

      SchoolHome home2 = (SchoolHome) IDOLookup.getHome(School.class);
      School school = home2.findByPrimaryKey(new Integer(schoolid));

      return school.getName();
    } catch (Exception e) {
      return "";
    }
  }
  private MemoryFileBuffer writeXls(IWContext iwc) throws IOException {
    MemoryFileBuffer buffer = new MemoryFileBuffer();
    MemoryOutputStream mos = new MemoryOutputStream(buffer);

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("Rejected students list");

    int rowNum = 0;

    HSSFRow row = sheet.createRow((short) rowNum++);
    fillHeaderRow(wb, sheet, row);

    // retrieve data
    Collection schoolChoices = getSchoolChoices(iwc);

    // fill data into rows
    if (!schoolChoices.isEmpty()) {
      User applicant;
      School school;
      Address address;
      Phone phone;
      SchoolChoice choice;
      String name = null;

      for (Iterator iter = schoolChoices.iterator(); iter.hasNext(); ) {
        choice = (SchoolChoice) iter.next();
        row = sheet.createRow((short) rowNum++);
        try {
          applicant = getUserBusiness(iwc).getUser(choice.getChildId());
          school =
              getSchoolCommuneBusiness(iwc)
                  .getSchoolBusiness()
                  .getSchool(new Integer(choice.getCurrentSchoolId()));
          address = getUserBusiness(iwc).getUsersMainAddress(applicant);

          name = getSchoolCommuneBusiness(iwc).getUserBusiness().getNameLastFirst(applicant, true);

          row.createCell((short) 0).setCellValue(name);

          if (applicant.getPersonalID() != null) {
            row.createCell((short) 1)
                .setCellValue(PersonalIDFormatter.format(applicant.getPersonalID(), this.locale));
          }

          String emails = this.getParentsEmails(iwc, applicant);
          if (emails != null) {
            row.createCell((short) 2).setCellValue(emails);
          }

          if (address != null) {
            row.createCell((short) 3).setCellValue(address.getStreetAddress());
            row.createCell((short) 4).setCellValue(address.getPostalCode().getPostalCode());
            row.createCell((short) 5).setCellValue(address.getCity());
          }

          try {
            phone = getUserBusiness(iwc).getUsersHomePhone(applicant);

            // getUserBusiness(iwc).getUsers
            if (phone != null && phone.getNumber() != null) {
              row.createCell((short) 6).setCellValue(phone.getNumber());
            }
          } catch (NoPhoneFoundException npfe) {
            npfe.printStackTrace();
          }

          String genderString = null;
          if (PIDChecker.getInstance().isFemale(applicant.getPersonalID())) {
            genderString = this.iwrb.getLocalizedString("school.girl", "Girl");
          } else {
            genderString = this.iwrb.getLocalizedString("school.boy", "Boy");
          }
          row.createCell((short) 7).setCellValue(genderString);

          if (school != null) {
            String schoolName = school.getName();
            row.createCell((short) 8).setCellValue(schoolName);
          }

          String rejectionDateString =
              getLocalizedTimestamp(iwc, getRejectionTimestamp(iwc, choice));
          if (rejectionDateString != null) {
            row.createCell((short) 9).setCellValue(rejectionDateString);
          }

        } catch (Exception e) {
          e.printStackTrace(System.err);
        }
      }
    }

    wb.write(mos);

    buffer.setMimeType("application/x-msexcel");
    return buffer;
  }
  /** @see se.idega.idegaweb.commune.school.report.business.ReportModel#buildCells() */
  protected void buildCells() {
    for (int column = 0; column < getColumnSize(); column++) {
      int row = 0;
      int columnMethod = 0;
      Object columnParameter = null;
      switch (column) {
        case 0:
          columnMethod = COLUMN_METHOD_SCHOOL_YEAR;
          columnParameter = "F";
          break;
        case 1:
          columnMethod = COLUMN_METHOD_SCHOOL_YEAR;
          columnParameter = "1";
          break;
        case 2:
          columnMethod = COLUMN_METHOD_SCHOOL_YEAR;
          columnParameter = "2";
          break;
        case 3:
          columnMethod = COLUMN_METHOD_SCHOOL_YEAR;
          columnParameter = "3";
          break;
        case 4:
          columnMethod = COLUMN_METHOD_SUM_1_3;
          columnParameter = null;
          break;
        case 5:
          columnMethod = COLUMN_METHOD_SCHOOL_YEAR;
          columnParameter = "4";
          break;
        case 6:
          columnMethod = COLUMN_METHOD_SCHOOL_YEAR;
          columnParameter = "5";
          break;
        case 7:
          columnMethod = COLUMN_METHOD_SCHOOL_YEAR;
          columnParameter = "6";
          break;
        case 8:
          columnMethod = COLUMN_METHOD_SUM_4_6;
          columnParameter = null;
          break;
        case 9:
          columnMethod = COLUMN_METHOD_SCHOOL_YEAR;
          columnParameter = "7";
          break;
        case 10:
          columnMethod = COLUMN_METHOD_SCHOOL_YEAR;
          columnParameter = "8";
          break;
        case 11:
          columnMethod = COLUMN_METHOD_SCHOOL_YEAR;
          columnParameter = "9";
          break;
        case 12:
          columnMethod = COLUMN_METHOD_SUM_7_9;
          columnParameter = null;
          break;
        case 13:
          columnMethod = COLUMN_METHOD_TOTAL_1_9;
          columnParameter = null;
          break;
        case 14:
          columnMethod = COLUMN_METHOD_TOTAL_F_9;
          columnParameter = null;
          break;
        case 15:
          columnMethod = COLUMN_METHOD_SCHOOL_YEAR;
          columnParameter = "0";
          break;
      }

      try {
        ReportBusiness rb = getReportBusiness();
        Collection areas = rb.getElementarySchoolAreas();
        Iterator areaIter = areas.iterator();
        while (areaIter.hasNext()) {
          SchoolArea area = (SchoolArea) areaIter.next();
          Collection schools = getReportBusiness().getElementarySchools(area);
          Iterator schoolIter = schools.iterator();
          while (schoolIter.hasNext()) {
            School school = (School) schoolIter.next();
            Object rowParameter = school.getPrimaryKey();
            Cell cell =
                new Cell(
                    this,
                    row,
                    column,
                    ROW_METHOD_SCHOOL,
                    columnMethod,
                    rowParameter,
                    columnParameter,
                    Cell.CELLTYPE_NORMAL);
            setCell(row, column, cell);
            row++;
          }
          Cell cell =
              new Cell(
                  this,
                  row,
                  column,
                  ROW_METHOD_SUM,
                  columnMethod,
                  null,
                  columnParameter,
                  Cell.CELLTYPE_SUM);
          setCell(row, column, cell);
          row++;
        }
        Cell cell =
            new Cell(
                this,
                row,
                column,
                ROW_METHOD_TOTAL,
                columnMethod,
                null,
                columnParameter,
                Cell.CELLTYPE_TOTAL);
        setCell(row, column, cell);
      } catch (RemoteException e) {
        log(e.getMessage());
      }
    }
  }
  public void main(IWContext iwc) throws Exception {

    String providerId = iwc.getParameter(CCConstants.PROVIDER_ID);
    String appId = iwc.getParameter(CCConstants.APPID);
    School school = getChildCareBusiness(iwc).getSchoolBusiness().getSchool(providerId);

    ChildCarePrognosis prognosis =
        getChildCareBusiness(iwc).getPrognosis(Integer.parseInt(providerId));

    String prognosisText =
        prognosis == null
            ? this.style.localize("ccpqw_no_prognosis", "No prognosis available")
            : this.style.localize("ccpqw_three_months", "Three months:")
                + " "
                + prognosis.getThreeMonthsPrognosis()
                + "  "
                + this.style.localize("ccpqw_one_year", "One year:")
                + " "
                + prognosis.getOneYearPrognosis()
                + "  "
                + this.style.localize("ccpqw_updated_date", "Updated date:")
                + " "
                + prognosis.getUpdatedDate();

    Table appTbl = new Table();

    //		add(new Text("ProviderId: " + providerId));
    if (providerId != null) {
      Collection applications =
          getChildCareBusiness(iwc)
              .getOpenAndGrantedApplicationsByProvider(new Integer(providerId).intValue());

      Iterator i = applications.iterator();

      appTbl.add(this.HEADER_ORDER, 1, 1);
      appTbl.add(this.HEADER_QUEUE_DATE, 2, 1);
      appTbl.add(this.HEADER_FROM_DATE, 3, 1);
      appTbl.setRowColor(1, this.style.getHeaderColor());

      int row = 2;

      while (i.hasNext()) {
        ChildCareApplication app = (ChildCareApplication) i.next();

        Text
            queueOrder =
                this.style.getSmallText("" + getChildCareBusiness(iwc).getNumberInQueue(app)),
            queueDate = this.style.getSmallText(app.getQueueDate().toString()),
            fromDate = this.style.getSmallText(app.getFromDate().toString());
        //					currentAppId = style.getSmallText(""+app.getNodeID());   //debug only

        appTbl.add(queueOrder, 1, row);
        appTbl.add(queueDate, 2, row);
        appTbl.add(fromDate, 3, row);
        //				appTbl.add(currentAppId, 4, row);  //debug only

        if (app.getNodeID() == new Integer(appId).intValue()) {
          emphasizeText(queueOrder);
          emphasizeText(queueDate);
          emphasizeText(fromDate);
        }

        if (row % 2 == 0) {
          appTbl.setRowColor(row, this.style.getZebraColor1());
        } else {
          appTbl.setRowColor(row, this.style.getZebraColor2());
        }

        row++;
      }
    }

    Table layoutTbl = new Table();
    layoutTbl.add(this.PROVIDER, 1, 1);
    layoutTbl.add(this.style.getSmallText(school.getName()), 2, 1);

    layoutTbl.setRowHeight(2, "20px");

    layoutTbl.add(this.PROGNOSIS, 1, 3);
    layoutTbl.add(this.style.getSmallText(prognosisText), 2, 3);

    layoutTbl.setRowHeight(4, "20px");

    layoutTbl.add(appTbl, 1, 5);
    layoutTbl.mergeCells(1, 5, 2, 5);

    CloseButton closeBtn = (CloseButton) this.style.getStyledInterface(new CloseButton(this.CLOSE));
    layoutTbl.add(closeBtn, 2, 6);
    layoutTbl.setAlignment(2, 6, "right");

    add(layoutTbl);
  }
  /**
   * Terminates all all high school placements not included in the import (except Nacka Gymnasium
   * placements).
   */
  protected boolean terminateOldPlacements() {
    println("NackaHighSchoolPlacementHandler: Starting termination of old placements...");
    boolean success = true;
    School schoolA = null;
    School schoolB = null;
    School schoolC = null;
    try {
      schoolA =
          schoolHome.findBySchoolName(NackaProgmaPlacementImportFileHandlerBean.SCHOOL_NAME_A);
    } catch (FinderException e) {
      println(
          "NackaHighSchoolPlacementHandler: School '"
              + NackaProgmaPlacementImportFileHandlerBean.SCHOOL_NAME_A
              + "' not found.");
      return false;
    }
    try {
      schoolB =
          schoolHome.findBySchoolName(NackaProgmaPlacementImportFileHandlerBean.SCHOOL_NAME_B);
    } catch (FinderException e) {
      println(
          "NackaHighSchoolPlacementHandler: School '"
              + NackaProgmaPlacementImportFileHandlerBean.SCHOOL_NAME_B
              + "' not found.");
      return false;
    }
    try {
      schoolC =
          schoolHome.findBySchoolName(NackaProgmaPlacementImportFileHandlerBean.SCHOOL_NAME_C);
    } catch (FinderException e) {
      println(
          "NackaHighSchoolPlacementHandler: School '"
              + NackaProgmaPlacementImportFileHandlerBean.SCHOOL_NAME_C
              + "' not found.");
      return false;
    }
    int schoolIdA = ((Integer) schoolA.getPrimaryKey()).intValue();
    int schoolIdB = ((Integer) schoolB.getPrimaryKey()).intValue();
    int schoolIdC = ((Integer) schoolC.getPrimaryKey()).intValue();
    String[] schoolIds =
        new String[] {
          String.valueOf(schoolIdA), String.valueOf(schoolIdB), String.valueOf(schoolIdC)
        };

    SchoolCategory highSchoolCategory = null;
    try {
      highSchoolCategory = schoolBusiness.getCategoryHighSchool();
    } catch (RemoteException e) {
      println("NackaHighSchoolPlacementHandler: High school category not found.");
      return false;
    }

    Collection placements = null;
    try {
      placements =
          schoolClassMemberHome.findActiveByCategorySeasonAndSchools(
              highSchoolCategory, season, schoolIds, true);
    } catch (FinderException e) {
      println("NackaHighSchoolPlacementHandler: Error finding placements.");
      return false;
    }

    Commune defaultCommune = null;
    try {
      defaultCommune =
          ((CommuneBusiness) getServiceInstance(CommuneBusiness.class)).getDefaultCommune();
    } catch (IBOLookupException e1) {
      e1.printStackTrace();
      println("NackaHighSchoolPlacementHandler: Unable to get default commune.");

      return false;
    } catch (RemoteException e1) {
      e1.printStackTrace();

      println("NackaHighSchoolPlacementHandler: Unable to get default commune.");
      return false;
    }

    Iterator iter = placements.iterator();
    IWTimestamp now = IWTimestamp.RightNow();
    now.setAsDate();
    while (iter.hasNext()) {
      SchoolClassMember member = (SchoolClassMember) iter.next();
      IWTimestamp placementDate = null;
      try {
        PlacementImportDate p = placementImportDateHome.findByPrimaryKey(member.getPrimaryKey());
        placementDate = new IWTimestamp(p.getImportDate());
        placementDate.setAsDate();
      } catch (FinderException e) {
      }
      School memberSchool = member.getSchoolClass().getSchool();
      if ((placementDate == null || placementDate.isEarlierThan(now))
          && (memberSchool.getManagementTypeId().equals(SchoolManagementTypeBMPBean.TYPE_COMMUNE))
          && (memberSchool.getCommune().equals(defaultCommune))) {
        member.setRemovedDate(lastDayInPreviousMonth);
        member.store();
        println("Terminating placement with id: " + member.getPrimaryKey());
      }
    }

    println("NackaHighSchoolPlacementHandler: Termination of old placements finished.");
    return success;
  }
  /** Stores one placement. */
  protected boolean storeUserInfo(int row) throws RemoteException {

    User user = null;
    SchoolType schoolType = null;
    School school = null;

    String providerName = getUserProperty(COLUMN_PROVIDER_NAME);
    if (providerName == null) {
      errorLog.put(new Integer(row), "The name of the high school is empty.");
      return false;
    }

    String schoolClassName = getUserProperty(COLUMN_SCHOOL_CLASS);
    if (schoolClassName == null) {
      errorLog.put(new Integer(row), "The class name is empty.");
      return false;
    }

    String schoolYearName = getUserProperty(COLUMN_SCHOOL_YEAR);
    if (schoolYearName == null) {
      errorLog.put(new Integer(row), "The school year is empty.");
    }

    String studyPathCode = getUserProperty(COLUMN_STUDY_PATH);
    if (studyPathCode == null) {
      studyPathCode = "";
    }

    String personalId = getUserProperty(COLUMN_PERSONAL_ID);
    if (personalId == null) {
      errorLog.put(new Integer(row), "The personal id is empty.");
      return false;
    }

    String studentName = getUserProperty(COLUMN_STUDENT_NAME);
    if (studentName == null) {
      studentName = "";
    }
    String studentFirstName = "";
    String studentLastName = "";
    if (studentName.length() > 0) {
      int cutPos = studentName.indexOf(',');
      if (cutPos != -1) {
        studentFirstName = studentName.substring(cutPos + 1).trim();
        studentLastName = studentName.substring(0, cutPos).trim();
      }
    }

    String homeCommuneCode = getUserProperty(COLUMN_HOME_COMMUNE);
    if (homeCommuneCode == null) {
      homeCommuneCode = "";
    }

    String address = getUserProperty(COLUMN_ADDRESS);
    if (address == null) {
      address = "";
    }

    String coAddress = getUserProperty(COLUMN_CO_ADDRESS);
    if (coAddress == null) {
      coAddress = "";
    }

    String zipCode = getUserProperty(COLUMN_ZIP_CODE);
    if (zipCode == null) {
      zipCode = "";
    }

    String zipArea = getUserProperty(COLUMN_ZIP_AREA);
    if (zipArea == null) {
      zipArea = "";
    }

    String highSchoolType = getUserProperty(COLUMN_HIGH_SCHOOL_TYPE);
    if (highSchoolType == null) {
      errorLog.put(new Integer(row), "The high school type is empty.");
      return false;
    }

    // user
    boolean isNewUser = false;
    try {
      user = communeUserBusiness.getUserHome().findByPersonalID(personalId);
    } catch (FinderException e) {
      println("User not found for PIN : " + personalId + " CREATING");

      try {
        user =
            communeUserBusiness.createSpecialCitizenByPersonalIDIfDoesNotExist(
                studentFirstName,
                "",
                studentLastName,
                personalId,
                getGenderFromPin(personalId),
                getBirthDateFromPin(personalId));
        isNewUser = true;
      } catch (Exception e2) {
        e2.printStackTrace();
        return false;
      }
    }

    if (isNewUser) {
      try {
        Commune homeCommune = communeHome.findByCommuneCode(homeCommuneCode);
        Integer communeId = (Integer) homeCommune.getPrimaryKey();
        communeUserBusiness.updateCitizenAddress(
            ((Integer) user.getPrimaryKey()).intValue(), address, zipCode, zipArea, communeId);
      } catch (FinderException e) {
        errorLog.put(new Integer(row), "Commune not found: " + homeCommuneCode);
        return false;
      }
      user.store();
    }

    // school type
    String typeKey = null;
    String schoolYearPrefix = "G";
    if (highSchoolType.equals("GY")) {
      typeKey = LOC_KEY_HIGH_SCHOOL;
    } else {
      typeKey = LOC_KEY_SPECIAL_HIGH_SCHOOL;
      schoolYearPrefix += "S";
    }

    try {
      schoolType = schoolTypeHome.findByTypeKey(typeKey);
    } catch (FinderException e) {
      errorLog.put(
          new Integer(row),
          "School type: " + highSchoolType + " not found in database (key = " + typeKey + ").");
      return false;
    }

    // school
    try {
      school = schoolHome.findBySchoolName(providerName);
    } catch (FinderException e) {
      errorLog.put(new Integer(row), "Cannot find school with name '" + providerName + "'");
      return false;
    }

    // school type
    boolean hasSchoolType = false;
    try {
      Iterator schoolTypeIter =
          schoolBusiness.getSchoolRelatedSchoolTypes(school).values().iterator();
      while (schoolTypeIter.hasNext()) {
        SchoolType st = (SchoolType) schoolTypeIter.next();
        if (st.getPrimaryKey().equals(schoolType.getPrimaryKey())) {
          hasSchoolType = true;
          break;
        }
      }
    } catch (Exception e) {
    }

    if (!hasSchoolType) {
      errorLog.put(
          new Integer(row),
          "School type '" + highSchoolType + "' not found in high school: " + providerName);
      return false;
    }

    // school year
    SchoolYear schoolYear = null;
    schoolYearName = schoolYearPrefix + schoolYearName;
    try {
      schoolYear = schoolYearHome.findByYearName(schoolYearName);
    } catch (FinderException e) {
      errorLog.put(new Integer(row), "School year: " + schoolYearName + " not found in database.");
    }
    boolean schoolYearFoundInSchool = false;
    Map m = schoolBusiness.getSchoolRelatedSchoolYears(school);
    try {
      schoolYearFoundInSchool = m.containsKey(schoolYear.getPrimaryKey());
    } catch (Exception e) {
    }

    if (!schoolYearFoundInSchool) {
      errorLog.put(
          new Integer(row),
          "School year: '" + schoolYearName + "' not found in school: '" + providerName + "'.");
      return false;
    }

    // study path
    SchoolStudyPath studyPath = null;
    try {
      studyPath = studyPathHome.findByCode(studyPathCode);
    } catch (Exception e) {
      errorLog.put(new Integer(row), "Cannot find study path: " + studyPathCode);
      return false;
    }

    // school Class
    SchoolClass schoolClass = null;
    try {
      int schoolId = ((Integer) school.getPrimaryKey()).intValue();
      int seasonId = ((Integer) season.getPrimaryKey()).intValue();
      Collection c = schoolClassHome.findBySchoolAndSeason(schoolId, seasonId);
      Iterator iter = c.iterator();
      while (iter.hasNext()) {
        SchoolClass sc = (SchoolClass) iter.next();
        if (sc.getName().equals(schoolClassName)) {
          schoolClass = sc;
          break;
        }
      }
      if (schoolClass == null) {
        throw new FinderException();
      }
    } catch (Exception e) {
      println(
          "School Class not found, creating '"
              + schoolClassName
              + "' for high school '"
              + providerName
              + "'.");
      int schoolId = ((Integer) school.getPrimaryKey()).intValue();
      int schoolTypeId = ((Integer) schoolType.getPrimaryKey()).intValue();
      int seasonId = ((Integer) season.getPrimaryKey()).intValue();
      try {
        schoolClass = schoolClassHome.create();
        schoolClass.setSchoolClassName(schoolClassName);
        schoolClass.setSchoolId(schoolId);
        schoolClass.setSchoolTypeId(schoolTypeId);
        schoolClass.setSchoolSeasonId(seasonId);
        schoolClass.setValid(true);
        schoolClass.store();
        schoolClass.addSchoolYear(schoolYear);
      } catch (Exception e2) {
      }

      if (schoolClass == null) {
        errorLog.put(new Integer(row), "Could not create school Class: " + schoolClassName);
        return false;
      }
    }

    // school Class member
    int schoolClassId = ((Integer) schoolClass.getPrimaryKey()).intValue();
    SchoolClassMember member = null;
    Timestamp registerDate = firstDayInCurrentMonth;

    try {
      Collection placements = schoolClassMemberHome.findByStudent(user);
      if (placements != null) {
        Iterator placementsIter = placements.iterator();
        while (placementsIter.hasNext()) {
          SchoolClassMember placement = (SchoolClassMember) placementsIter.next();
          SchoolType st = placement.getSchoolClass().getSchoolType();
          String stKey = "";

          if (st != null) {
            stKey = st.getLocalizationKey();
          }

          if (stKey.equals(LOC_KEY_HIGH_SCHOOL) || stKey.equals(LOC_KEY_SPECIAL_HIGH_SCHOOL)) {
            if (placement.getRemovedDate() == null) {
              int scId = placement.getSchoolClassId();
              int studyPathId = placement.getStudyPathId();
              int newStudyPathId = ((Integer) studyPath.getPrimaryKey()).intValue();
              int schoolYearId = placement.getSchoolYearId();
              int newSchoolYearId = ((Integer) schoolYear.getPrimaryKey()).intValue();
              if ((scId == schoolClassId)
                  && (studyPathId == newStudyPathId)
                  && (schoolYearId == newSchoolYearId)) {
                member = placement;
              } else {
                IWTimestamp t1 = new IWTimestamp(placement.getRegisterDate());
                t1.setAsDate();
                IWTimestamp t2 = new IWTimestamp(firstDayInCurrentMonth);
                t2.setAsDate();
                if (t1.equals(t2)) {
                  try {
                    PlacementImportDate p = null;
                    try {
                      p = placementImportDateHome.findByPrimaryKey(placement.getPrimaryKey());
                    } catch (FinderException e) {
                    }
                    if (p != null) {
                      p.remove();
                    }
                    placement.remove();
                  } catch (RemoveException e) {
                    log(e);
                  }
                } else {
                  placement.setRemovedDate(lastDayInPreviousMonth);
                  placement.store();
                }
                registerDate = firstDayInCurrentMonth;
              }
            }
          }
        }
      }
    } catch (FinderException f) {
    }

    if (member == null) {
      try {
        member = schoolClassMemberHome.create();
      } catch (CreateException e) {
        errorLog.put(
            new Integer(row),
            "School Class member could not be created for personal id: " + personalId);
        return false;
      }
      member.setSchoolClassId(((Integer) schoolClass.getPrimaryKey()).intValue());
      member.setClassMemberId(((Integer) user.getPrimaryKey()).intValue());
      member.setRegisterDate(registerDate);
      member.setRegistrationCreatedDate(IWTimestamp.getTimestampRightNow());
      member.setSchoolYear(((Integer) schoolYear.getPrimaryKey()).intValue());
      member.setSchoolTypeId(((Integer) schoolType.getPrimaryKey()).intValue());
      member.setStudyPathId(((Integer) studyPath.getPrimaryKey()).intValue());
      member.store();
    }

    PlacementImportDate p = null;
    try {
      p = placementImportDateHome.findByPrimaryKey(member.getPrimaryKey());
    } catch (FinderException e) {
    }
    if (p == null) {
      try {
        p = placementImportDateHome.create();
        p.setSchoolClassMemberId(((Integer) member.getPrimaryKey()).intValue());
      } catch (CreateException e) {
        errorLog.put(
            new Integer(row),
            "Could not create import date from school class member: " + member.getPrimaryKey());
        return false;
      }
    }
    p.setImportDate(today);
    p.store();

    return true;
  }
  /**
   * Send message and e-mail to all administrators for schools belonging to the specified
   * operational fields.
   *
   * @param subject the message subject
   * @param body the message body
   * @param operationalFields the operational field ids
   * @param onlyHomeCommune if true then messages are only sent to home commune schools
   * @return a collection of {school_name, headmaster}
   * @throws NoticeException if incomplete parameters or technical send error
   */
  public Collection sendNotice(
      String subject, String body, String[] operationalFields, boolean onlyHomeCommune)
      throws NoticeException {
    if (body.equals("")) {
      throw new NoticeException(KEY_EMPTY_BODY, DEFAULT_EMPTY_BODY);
    }
    if (body.length() > 4000) {
      body = body.substring(0, 4000);
    }
    if (operationalFields == null) {
      throw new NoticeException(KEY_OPERATIONAL_FIELDS_EMPTY, DEFAULT_OPERATIONAL_FIELDS_EMPTY);
    }
    Map schoolCategories = new HashMap();
    for (int i = 0; i < operationalFields.length; i++) {
      schoolCategories.put(operationalFields[i], operationalFields[i]);
    }
    int homeCommuneId = 0;
    try {
      CommuneHome communeHome = (CommuneHome) getIDOHome(Commune.class);
      Commune homeCommune = communeHome.findDefaultCommune();
      homeCommuneId = ((Integer) homeCommune.getPrimaryKey()).intValue();
    } catch (Exception e) {
    }

    Collection c = new ArrayList();
    try {
      SchoolBusiness sb = getSchoolBusiness();
      SchoolCategory childCareCategory = sb.getCategoryChildcare();
      String childCareCategoryId = childCareCategory.getCategory();
      HashMap messageReceivers = new HashMap();
      HashMap emailReceivers = new HashMap();
      Collection schoolTypes = sb.findAllSchoolTypes();
      Iterator iter = schoolTypes.iterator();
      while (iter.hasNext()) {
        SchoolType st = (SchoolType) iter.next();
        String sc = st.getSchoolCategory();
        if (!schoolCategories.containsKey(sc)) {
          continue;
        }
        int schoolTypeId = ((Integer) st.getPrimaryKey()).intValue();
        Collection schools = sb.findAllSchoolsByType(schoolTypeId);
        Iterator iter2 = schools.iterator();
        while (iter2.hasNext()) {
          School school = (School) iter2.next();
          if (onlyHomeCommune) {
            if (school.getCommuneId() != homeCommuneId) {
              continue;
            }
          }
          Collection users = sb.getSchoolUsers(school);
          Iterator iter3 = users.iterator();
          while (iter3.hasNext()) {
            SchoolUser schoolUser = (SchoolUser) iter3.next();
            User user = schoolUser.getUser();
            Provider provider = new Provider(school);
            if (!sc.equals(childCareCategoryId)
                || (!school.getCentralizedAdministration() && !provider.getPaymentByInvoice())) {
              if (messageReceivers.get(user.getPrimaryKey()) == null) {
                String[] s = new String[2];
                s[0] = school.getName();
                s[1] = user.getName();
                c.add(s);
                boolean sendEMail = true;
                Email email = getUserBusiness().getUserMail(user);
                String emailAddress = null;
                if (email != null) {
                  emailAddress = email.getEmailAddress();
                }
                if (emailAddress != null) {
                  if (emailReceivers.get(emailAddress) != null) {
                    sendEMail = false;
                  }
                  emailReceivers.put(emailAddress, user);
                }
                Message message =
                    getMessageBusiness()
                        .createUserMessage(
                            null, user, null, null, subject, body, body, false, null, false,
                            sendEMail);
                message.store();
                messageReceivers.put(user.getPrimaryKey(), user);
              }
            }
          }
        }
      }
    } catch (RemoteException e) {
      throw new NoticeException(KEY_SYSTEM_ERROR, DEFAULT_SYSTEM_ERROR);
    }
    return c;
  }