public Map<String, String> getUriToDocument(
      FileDownloadNotificationProperties properties, String identifier, List<User> users) {
    if (properties == null || ListUtil.isEmpty(users)) {
      return null;
    }

    Map<String, String> uris = new HashMap<String, String>(users.size());
    for (User user : users) {
      uris.put(user.getId(), properties.getUrl());
    }
    return uris;
  }
 public Collection<Phone> getPhones() {
   IWContext iwc = getIwc();
   if (!iwc.isLoggedOn()) {
     return Collections.emptyList();
   }
   User user = iwc.getCurrentUser();
   @SuppressWarnings("unchecked")
   Collection<Phone> phones = user.getPhones();
   if (ListUtil.isEmpty(phones)) {
     return Collections.emptyList();
   }
   return phones;
 }
 public Collection<Email> getEmails() {
   IWContext iwc = getIwc();
   if (!iwc.isLoggedOn()) {
     return Collections.emptyList();
   }
   User user = iwc.getCurrentUser();
   @SuppressWarnings("unchecked")
   Collection<Email> emails = user.getEmails();
   if (ListUtil.isEmpty(emails)) {
     return Collections.emptyList();
   }
   return emails;
 }
  public Table getListTable(IWContext iwc) throws RemoteException {
    Table table = new Table(2, this.USERS_PER_PAGE + 1);
    table.setCellspacing(0);
    table.setCellpadding(2);
    table.setWidth(Table.HUNDRED_PERCENT);
    table.setHorizontalZebraColored(
        IWConstants.DEFAULT_INTERFACE_COLOR, IWConstants.DEFAULT_LIGHT_INTERFACE_COLOR);
    int row = 1;
    int rowHeight = 12;
    table.setHeight(table.getRows() * rowHeight);

    table.add(getTitleText(localize("user", "User")), 1, row);
    table.add(getTitleText(localize("personal_id", "Personal ID")), 2, row);
    table.setRowColor(row, IWConstants.DEFAULT_DARK_INTERFACE_COLOR);
    table.setHeight(row, rowHeight);

    if (this.users != null) {
      /** Calculating page....starts */
      int start = this.currentPage * this.USERS_PER_PAGE;
      Iterator iter = this.users.iterator();
      for (int i = 0; i < start; i++) {
        if (iter.hasNext()) {
          iter.next();
        }
      }
      /** Calculating page....ends */
      int counter = 0;
      User user;
      Link link;
      String pId;
      while (iter.hasNext() && counter < this.USERS_PER_PAGE) {
        ++counter;
        ++row;
        table.setHeight(row, rowHeight);

        user = (User) iter.next();
        pId = user.getPersonalID();
        if (pId == null) {
          pId = "-";
        }
        link = getLink(getText(user.getName()), iwc);
        link.addParameter(this.PARAMETER_USER_ID, user.getPrimaryKey().toString());
        table.add(link, 1, row);
        table.add(getText(pId), 2, row);
      }
    }

    return table;
  }
  public Table getListTable(IWContext iwc) throws RemoteException {
    Table table = new Table(3, this.USERS_PER_PAGE + 1);
    table.setCellspacing(0);
    table.setCellpadding(2);
    table.setWidth("100%");
    table.setHorizontalZebraColored("#C1C3B4", "#FFFFFF");
    int row = 1;
    int rowHeight = 12;
    table.setHeight(table.getRows() * rowHeight);
    table.add(getTitleText(localize("user", "User")), 1, row);
    table.add(getTitleText(localize("school", "School")), 2, row);
    table.add(getTitleText(localize("personal_id", "Personal ID")), 3, row);
    table.setRowColor(row, "#74858D");
    table.setHeight(row, rowHeight);

    if (this.users != null) {
      int start = this.currentPage * this.USERS_PER_PAGE;
      Iterator iter = this.users.iterator();
      for (int i = 0; i < start; i++) {
        if (iter.hasNext()) {
          iter.next();
        }
      }

      String pId;
      for (int counter = 0;
          iter.hasNext() && counter < this.USERS_PER_PAGE;
          table.add(getText(pId), 3, row)) {
        counter++;
        row++;
        table.setHeight(row, rowHeight);
        User user = (User) iter.next();
        pId = user.getPersonalID();
        if (pId == null) {
          pId = "-";
        }
        Link link = getLink(getText(user.getName()), iwc);

        link.addParameter(this.PARAMETER_USER_ID, user.getPrimaryKey().toString());
        table.add(link, 1, row);

        table.add(getText(getSchoolName(user)), 2, row);
      }
    }
    return table;
  }
  public School getProvider() throws RemoteException {
    if (getUserContext().isLoggedOn()) {
      User user = getUserContext().getCurrentUser();
      Object userID = user.getPrimaryKey();

      if (this.iUserPK != null && this.iUserPK.equals(userID)) {
        if (this.iProvider != null) {
          return this.iProvider;
        } else {
          return getSchoolIDFromUser(user);
        }
      } else {
        this.iUserPK = userID;
        return getSchoolIDFromUser(user);
      }
    } else {
      return null;
    }
  }
 /*
  * (non-Javadoc)
  *
  * @see is.idega.idegaweb.member.presentation.UserEditor#getCommune(com.idega.user.data.User)
  */
 protected Commune getCommune(IWContext iwc, User user) {
   try {
     if (user != null) {
       CommuneUserBusiness communeUserService = getCommuneUserService(iwc);
       Group communeGroup = communeUserService.getRootCitizenGroup();
       Integer ID =
           communeGroup != null ? (Integer) communeGroup.getPrimaryKey() : new Integer(-1);
       if (user.getPrimaryGroupID() == ID.intValue() || user.hasRelationTo(communeGroup)) {
         if (super.showDefaultCommuneOption) {
           return getCommuneBusiness(iwc).getCommuneHome().findDefaultCommune();
         } else {
           return null;
         }
       }
     }
   } catch (Exception e) {
     e.printStackTrace(System.err);
   }
   return null;
 }
  public void main(IWContext iwc) throws Exception {
    _iwc = iwc;

    userID = iwc.getUserId();

    if (userID > 0) {
      user = ((UserBusiness) IBOLookup.getServiceInstance(iwc, UserBusiness.class)).getUser(userID);
    }

    imageCircleD = getBundle(iwc).getImage("circleDown.gif");
    imageCircleU = getBundle(iwc).getImage("circleUp.gif");
    imageBgVert = getBundle(iwc).getImage("bgbeigeVert.gif");
    imageBgVertOut = getBundle(iwc).getImage("bgbeigeVert1.gif");

    //	add(getOverviewForm(iwc));
    if (user != null && user.getDateOfBirth() != null) age = new Age(user.getDateOfBirth());
    else if (user != null && user.getPersonalID() != null)
      age = new Age(PIDChecker.getInstance().getDateFromPersonalID(user.getPersonalID()));

    add(getOverviewForm());
  }
  public Object addComment(CommentsViewerProperties properties) {
    if (properties == null || properties.getEntryId() == null) {
      LOGGER.warning("Properties are not provided or entry ID is unknown: " + properties);
      return null;
    }

    try {
      boolean hasFullRightsForComments = hasFullRightsForComments(properties.getIdentifier());

      CommentHome commentHome = getCommentHome();
      Comment comment = commentHome.create();

      comment.setEntryId(properties.getEntryId());
      comment.setCommentHolder(String.valueOf(properties.getIdentifier()));

      boolean hasReplyToId =
          properties.getReplyForComment() == null
              ? false
              : properties.getReplyForComment() < 0 ? false : true;
      boolean privateComment = hasReplyToId || !hasFullRightsForComments;
      comment.setPrivateComment(privateComment);
      comment.setReplyForCommentId(properties.getReplyForComment());
      comment.setAnnouncedToPublic(hasFullRightsForComments && !privateComment);

      User author = getLoggedInUser();
      if (author != null) {
        comment.setAuthorId(Integer.valueOf(author.getId()));
      }
      comment.store();

      addAttachment(properties, comment);

      return comment.getPrimaryKey();
    } catch (Exception e) {
      LOGGER.log(Level.WARNING, "Error creating " + Comment.class, e);
    }

    return null;
  }
  public String getUserNameDWR(String personalID, String localeStr) {
    try {
      if (personalID != null && !personalID.trim().equals("")) {
        UserHome uHome = (UserHome) IDOLookup.getHome(User.class);
        User user = uHome.findByPersonalID(personalID);
        return user.getName();
      } else {
        return "";
      }
    } catch (IDOLookupException e) {
      e.printStackTrace();
    } catch (FinderException e) {
    }

    try {
      IWContext iwc = IWContext.getInstance();
      Locale locale = iwc.getCurrentLocale();
      IWResourceBundle iwrb = getBundle().getResourceBundle(locale);
      return iwrb.getLocalizedString("landsmot.user_not_found", "User not found");
    } catch (UnavailableIWContext e) {
      return "User not found";
    }
  }
  /**
   * @see
   *     com.idega.presentation.ui.AbstractChooserWindow#displaySelection(com.idega.presentation.IWContext)
   */
  public void displaySelection(IWContext iwc) {
    String uId = iwc.getParameter(this.PARAMETER_USER_ID);
    if (uId != null) {
      try {
        User user = getUserHome().findByPrimaryKey(new Integer(uId));
        Page page = getParentPage();
        page.setOnLoad(SELECT_FUNCTION_NAME + "('" + user.getName() + "','" + uId + "')");
      } catch (RemoteException e) {
      } catch (FinderException e) {
      }
    } else {

      init(iwc);

      addTitle(this.iwrb.getLocalizedString("select_a_user", "Select a user"), TITLE_STYLECLASS);

      this.form.maintainParameter(SCRIPT_PREFIX_PARAMETER);
      this.form.maintainParameter(SCRIPT_SUFFIX_PARAMETER);
      this.form.maintainParameter(DISPLAYSTRING_PARAMETER_NAME);
      this.form.maintainParameter(VALUE_PARAMETER_NAME);

      Table mainTable = new Table(1, 4);
      mainTable.setStyleClass(this.mainTableStyle);
      mainTable.setWidth(Table.HUNDRED_PERCENT);
      mainTable.setBorder(0);

      mainTable.add(getHeaderTable(iwc), 1, 1);
      mainTable.add(getNavigationTable(iwc), 1, 3);
      try {
        mainTable.add(getListTable(iwc), 1, 4);
      } catch (RemoteException r) {
        throw new RuntimeException(r.getMessage());
      }
      this.form.add(mainTable);
      add(this.form, iwc);
    }
  }
  Collection<Object> ejbFindAllCommentsForUser(User author, String commentHolder)
      throws FinderException {
    Table table = new Table(this);
    SelectQuery query = new SelectQuery(table);
    query.addColumn(new Column(table, getIDColumnName()));

    query.addCriteria(
        new MatchCriteria(new Column(table, COLUMN_AUTHOR), MatchCriteria.EQUALS, author.getId()));
    query.addCriteria(
        new MatchCriteria(
            new Column(table, COLUMN_COMMENT_HOLDER), MatchCriteria.EQUALS, commentHolder));
    addNotDeletedCriteria(query, table);

    return this.idoFindPKsByQuery(query);
  }
  public String getUriToAttachment(String commentId, ICFile attachment, User user) {
    URIUtil uri = new URIUtil(IWMainApplication.getDefaultIWMainApplication().getMediaServletURI());

    uri.setParameter(
        MediaWritable.PRM_WRITABLE_CLASS,
        IWMainApplication.getEncryptedClassName(CommentAttachmentDownloader.class));
    uri.setParameter(ArticleCommentAttachmentStatisticsViewer.COMMENT_ID_PARAMETER, commentId);
    uri.setParameter(
        ArticleCommentAttachmentStatisticsViewer.COMMENT_ATTACHMENT_ID_PARAMETER,
        attachment.getPrimaryKey().toString());

    if (user != null) {
      uri.setParameter(LoginBusinessBean.PARAM_LOGIN_BY_UNIQUE_ID, user.getUniqueId());
      uri.setParameter(LoginBusinessBean.LoginStateParameter, LoginBusinessBean.LOGIN_EVENT_LOGIN);
    }

    return uri.getUri();
  }
  public Table getPupilTable(IWContext iwc, User pupil) {
    // *** Search Table *** START - the uppermost table
    Table table = new Table();
    table.setWidth("100%");
    table.setBorder(0);
    table.setCellpadding(2);
    table.setCellspacing(0);
    this.transGIF.setHeight("1");
    this.transGIF.setWidth("1");

    int row = 1;
    int col = 1;
    // add empty space row
    table.add(this.transGIF, col++, row);
    table.add(this.transGIF, col++, row);
    table.add(this.transGIF, col++, row);
    table.add(this.transGIF, col++, row);
    table.add(this.transGIF, col++, row);
    // Set COLUMN WIDTH for column 1 to 5
    table.setWidth(1, row, "100");
    // table.setWidth(2, row, "70");
    // table.setWidth(3, row, "70");
    // table.setWidth(4, row, "70");
    // table.setWidth(5, row, "104");

    row++;
    col = 1;

    // *** HEADING Pupil ***
    Text pupilTxt = new Text(localize(KEY_PUPIL_HEADING, "Pupil"));
    pupilTxt.setFontStyle(STYLE_UNDERLINED_SMALL_HEADER);
    table.add(pupilTxt, col++, row);
    table.setRowHeight(row, "20");
    table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
    row++;
    col = 1;

    // empty space row
    table.add(this.transGIF, col, row);
    table.setRowHeight(row, "5");
    col = 1;
    row++;

    // Personal Id Number
    table.add(getSmallHeader(localize(KEY_PERSONAL_ID_LABEL, "Personal id: ")), col++, row);
    if (pupil != null) {
      table.add(getSmallText(pupil.getPersonalID()), col++, row);
    }
    row++;
    col = 1;
    // Last Name
    table.add(getSmallHeader(localize(KEY_LAST_NAME_LABEL, "Last name: ")), col++, row);

    Table nameTable = new Table();
    col = 1;
    nameTable.setCellpadding(0);
    nameTable.setCellspacing(0);
    if (pupil != null) {
      nameTable.add(getSmallText(pupil.getLastName()), col++, 1);
    }
    // First Name
    nameTable.add(getSmallHeader(localize(KEY_FIRST_NAME_LABEL, "First name: ")), col++, 1);
    if (pupil != null) {
      nameTable.add(getSmallText(pupil.getFirstName()), col++, 1);
    }
    nameTable.setWidth(1, 1, "100");
    nameTable.setWidth(2, 1, "100");
    nameTable.setWidth(3, 1, "100");
    table.add(nameTable, 2, row);
    table.mergeCells(2, row, 5, row);
    row++;
    col = 1;

    // Address and Phone
    table.add(getSmallHeader(localize(KEY_ADDRESS_LABEL, "Address: ")), col++, row);
    row++;
    col = 1;
    table.add(getSmallHeader(localize(KEY_PHONE_LABEL, "Phone: ")), col++, row);
    if (pupil != null) {
      try {
        // pupil address
        Address address = getUserBusiness(iwc).getUsersMainAddress(pupil);
        StringBuffer aBuf = new StringBuffer(address.getStreetAddress());
        aBuf.append(", ");
        aBuf.append(address.getPostalCode().getPostalAddress());
        row--;
        table.add(getSmallText(aBuf.toString()), col, row);
        row++;
        // Get pupil phones
        Collection phones = pupil.getPhones();
        int i = 0;
        int phonesSize = phones.size();
        StringBuffer pBuf = new StringBuffer();
        for (Iterator iter = phones.iterator(); iter.hasNext(); i++) {
          Phone phone = (Phone) iter.next();
          pBuf.append(phone.getNumber());
          if (i < phonesSize - 1) {
            pBuf.append(", ");
          }
        }
        pBuf.append("&nbsp;");
        table.add(getSmallText(pBuf.toString()), col, row);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    row++;
    col = 1;

    return table;
  }
  private Table2 getRaceParticipantListForEvent(
      IWContext iwc, List eventParticipants, RaceEvent raceEvent) throws RemoteException {
    Table2 table = new Table2();
    table.setStyleClass("raceParticipantTable");
    table.setStyleClass("ruler");
    table.setWidth("100%");
    table.setCellpadding(0);
    table.setCellspacing(0);

    TableRowGroup group = table.createHeaderRowGroup();
    TableRow row = group.createRow();
    TableCell2 cell = row.createHeaderCell();
    cell.setStyleClass("firstColumn");
    cell.setStyleClass("raceNumber");
    cell.add(
        new Text(getResourceBundle().getLocalizedString("race_participant_list.race_number", "#")));

    cell = row.createHeaderCell();
    cell.setStyleClass("name");
    cell.add(
        new Text(getResourceBundle().getLocalizedString("race_participant_list.name", "Name")));

    cell = row.createHeaderCell();
    cell.setStyleClass("raceVehicle");
    cell.add(
        new Text(
            getResourceBundle()
                .getLocalizedString("race_participant_list.race_vehicle", "Race vehicle")));

    cell = row.createHeaderCell();
    cell.setStyleClass("raceVehicleSubtype");
    cell.add(
        new Text(
            getResourceBundle()
                .getLocalizedString("race_participant_list.race_vehicle_subtype", "Subtype")));

    cell = row.createHeaderCell();
    cell.setStyleClass("raceEngineCC");
    cell.add(
        new Text(
            getResourceBundle()
                .getLocalizedString("race_participant_list.race_engine_CC", "Engine CC")));

    cell = row.createHeaderCell();
    cell.setStyleClass("raceEngine");
    cell.add(
        new Text(
            getResourceBundle().getLocalizedString("race_participant_list.race_engine", "Engine")));

    cell = row.createHeaderCell();
    cell.setStyleClass("raceTeam");
    cell.add(
        new Text(
            getResourceBundle().getLocalizedString("race_participant_list.race_team", "Team")));

    cell = row.createHeaderCell();
    cell.setStyleClass("raceSponsor");
    cell.add(
        new Text(
            getResourceBundle()
                .getLocalizedString("race_participant_list.race_sponsor", "Sponsor")));

    group = table.createBodyRowGroup();
    int iRow = 1;

    if (!ListUtil.isEmpty(eventParticipants)) {
      Iterator iter = eventParticipants.iterator();
      while (iter.hasNext()) {
        Participant participant = (Participant) iter.next();
        if (participant == null) {
          getLogger().warning("Participant is unknown for race event: " + raceEvent);
          continue;
        }

        row = group.createRow();

        User user = null;
        RaceUserSettings settings = null;
        try {
          user = participant.getUser();
          settings = this.getRaceBusiness(iwc).getRaceUserSettings(user);
        } catch (Exception e) {
          getLogger()
              .log(
                  Level.WARNING,
                  "Error getting settings for participant "
                      + participant
                      + ", user: "******"" : "(ID: " + user.getId() + ")")
                      + ". Race event: "
                      + raceEvent,
                  e);
        }
        if (user == null) {
          getLogger()
              .warning(
                  "User can not be found for participant "
                      + participant
                      + ", race event: "
                      + raceEvent);
        }
        if (settings == null) {
          getLogger()
              .warning(
                  "Settings can not be found for participant "
                      + participant
                      + ", race event: "
                      + raceEvent);
        }

        if (iRow == 1) {
          row.setStyleClass("firstRow");
        } else if (!iter.hasNext()) {
          row.setStyleClass("lastRow");
        }

        cell = row.createCell();
        cell.setStyleClass("firstColumn");
        cell.setStyleClass("raceNumber");
        cell.add(new Text(participant.getRaceNumber() != null ? participant.getRaceNumber() : ""));

        cell = row.createCell();
        cell.setStyleClass("name");
        cell.add(new Text(user != null ? user.getName() : ""));

        cell = row.createCell();
        cell.setStyleClass("raceVehicle");
        String raceVehicleString = "";
        if (settings != null && settings.getVehicleType() != null) {
          raceVehicleString =
              getResourceBundle()
                  .getLocalizedString(
                      settings.getVehicleType().getLocalizationKey(),
                      settings.getVehicleType().getLocalizationKey());
        }
        cell.add(new Text(raceVehicleString));

        cell = row.createCell();
        cell.setStyleClass("raceVehicleSubtype");
        String raceVehicleSubtypeString = "";
        if (settings != null && settings.getVehicleSubType() != null) {
          raceVehicleSubtypeString =
              getResourceBundle()
                  .getLocalizedString(
                      settings.getVehicleSubType().getLocalizationKey(),
                      settings.getVehicleSubType().getLocalizationKey());
        }
        cell.add(new Text(raceVehicleSubtypeString));

        cell = row.createCell();
        cell.setStyleClass("raceEngineCC");
        cell.add(
            new Text(
                settings == null
                    ? ""
                    : settings.getEngineCC() != null ? settings.getEngineCC() : ""));

        cell = row.createCell();
        cell.setStyleClass("raceEngine");
        cell.add(
            new Text(
                settings == null ? "" : settings.getEngine() != null ? settings.getEngine() : ""));

        cell = row.createCell();
        cell.setStyleClass("raceTeam");
        cell.add(
            new Text(settings == null ? "" : settings.getTeam() != null ? settings.getTeam() : ""));

        StringBuffer sponsorString = new StringBuffer("");
        if (settings != null && settings.getSponsor() != null) {
          if (settings.getSponsor().length() > 30) {
            sponsorString.append(settings.getSponsor().substring(0, 30));
          } else {
            sponsorString.append(settings.getSponsor());
          }
        }
        cell = row.createCell();
        cell.setStyleClass("raceSponsor");
        cell.add(new Text(sponsorString.toString()));

        if (iRow % 2 == 0) {
          row.setStyleClass("evenRow");
        } else {
          row.setStyleClass("oddRow");
        }

        iRow++;
      }
    } else {
      getLogger().warning("Participants not provided");
    }

    return table;
  }
  /**
   * @param updateName
   * @param user
   */
  public User handleNames(
      User user,
      String firstName,
      String middleName,
      String lastName,
      String preferredNameIndex,
      boolean store) {
    boolean updateName = false;

    if (firstName == null || firstName.trim().equals("")) {
      if (user.getFirstName() != null) {
        firstName = user.getFirstName();
      } else {
        firstName = "";
      }
    }
    /*
     * Setting middleName as "", required for the rest of the code
     */
    if (middleName != null && !middleName.equals("")) {
      firstName = firstName + " " + middleName;
      middleName = "";
    } else {
      middleName = "";
    }

    if (lastName == null || lastName.trim().equals("")) {
      if (user.getLastName() != null) {
        lastName = user.getLastName();
      } else {
        lastName = "";
      }
    }

    if (preferredNameIndex == null) {
      preferredNameIndex = "10";
    }

    StringBuffer fullname = new StringBuffer();
    /*
     * Preferred name handling.
     */
    if (preferredNameIndex != null) {

      fullname.append(firstName).append(" ").append(middleName).append(" ").append(lastName);

      int index = Integer.parseInt(preferredNameIndex);
      int refName1 = index / 10;
      int refName2 = index % 10;

      if (refName2 > 0) {
        String fullName = fullname.toString();

        String preferredName1 = getValueAtIndexFromNameString(refName1, fullName);
        String preferredName2 = getValueAtIndexFromNameString(refName2, fullName);

        firstName = preferredName1 + " " + preferredName2;
        firstName = TextSoap.findAndReplace(firstName, "  ", " ");

        /*
         * Remember MIDDLE NAME is always "" in the beginning. Removing
         * lastName since last name should only be changed when moving
         * name to firstName
         */
        middleName = TextSoap.findAndCut(fullName, lastName);
        middleName = TextSoap.findAndCut(middleName, preferredName1);
        middleName = TextSoap.findAndCut(middleName, preferredName2);
        middleName = TextSoap.findAndReplace(middleName, "  ", " ");

        lastName = TextSoap.findAndCut(lastName, preferredName2);
        lastName = TextSoap.findAndReplace(lastName, "  ", " ");

        updateName = true;
      } else if (refName1 > 0) {
        String fullName = fullname.toString();

        String preferredName = getValueAtIndexFromNameString(refName1, fullName);
        if (middleName.equals("")) {
          middleName = firstName;
        } else {
          if (middleName.startsWith(" ")) {
            middleName = firstName + middleName;
          } else {
            middleName = firstName + " " + middleName;
          }
        }

        firstName = preferredName;
        middleName = TextSoap.findAndCut(middleName, preferredName);
        middleName = TextSoap.findAndReplace(middleName, "  ", " ");
        if (refName1 > 1 && !lastName.equals(preferredName)) {
          lastName = TextSoap.findAndCut(lastName, preferredName);
          lastName = TextSoap.findAndReplace(lastName, "  ", " ");
        }

        updateName = true;
      }
    }

    if (lastName.startsWith("Van ") && !updateName) {
      StringBuffer half = new StringBuffer();
      half.append(firstName).append(" ").append(middleName);
      String halfName = half.toString();
      firstName = getValueAtIndexFromNameString(1, halfName);
      middleName =
          halfName.substring(
              Math.min(halfName.indexOf(" ") + 1, halfName.length()), halfName.length());
      middleName = TextSoap.findAndReplace(middleName, "  ", " ");

      updateName = true;
    }

    /*
     * Needed because createUser uses the method setFullName that splits the
     * name with it's own rules
     */
    if (updateName) {
      if (firstName != null) {
        if (firstName.endsWith(" ")) {
          firstName = firstName.substring(0, firstName.length() - 1);
        }
      }

      if (middleName != null) {
        if (middleName.startsWith(" ")) {
          middleName = middleName.substring(1, middleName.length());
        }
        if (middleName.endsWith(" ")) {
          middleName = middleName.substring(0, middleName.length() - 1);
        }
      }

      if (lastName != null) {
        if (lastName.startsWith(" ")) {
          lastName = lastName.substring(1, lastName.length());
        }
        if (lastName.endsWith(" ")) {
          lastName = lastName.substring(0, lastName.length() - 1);
        }
      }

      user.setFirstName(firstName);
      user.setMiddleName(middleName);
      user.setLastName(lastName);
    }

    if (store) {
      try {
        user.store();
      } catch (IDOStoreException e) {
        throw e;
      }
    }
    return user;
  }
  private void updatePreferences(IWContext iwc) throws Exception {
    LoginTable loginTable =
        LoginDBHandler.getUserLogin(((Integer) user.getPrimaryKey()).intValue());
    String login = loginTable.getUserLogin();
    String currentPassword = iwc.getParameter(PARAMETER_CURRENT_PASSWORD);
    String newPassword1 = iwc.getParameter(PARAMETER_NEW_PASSWORD);
    String newPassword2 = iwc.getParameter(PARAMETER_NEW_PASSWORD_REPEATED);

    String errorMessage = null;
    boolean updatePassword = false;

    try {

      // if authorized by bank id we allow the user change his preferences
      if (authorizedByBankID(iwc)) {

      } else if (requirePasswordVerification
          && !LoginDBHandler.verifyPassword(login, currentPassword)) {
        throw new Exception(localize(KEY_PASSWORD_INVALID, DEFAULT_PASSWORD_INVALID));
      }

      // Validate new password
      if (!newPassword1.equals("") || !newPassword2.equals("")) {
        if (newPassword1.equals("")) {
          throw new Exception(localize(KEY_PASSWORD_EMPTY, DEFAULT_PASSWORD_EMPTY));
        }
        if (newPassword2.equals("")) {
          throw new Exception(
              localize(KEY_PASSWORD_REPEATED_EMPTY, DEFAULT_PASSWORD_REPEATED_EMPTY));
        }
        if (!newPassword1.equals(newPassword2)) {
          throw new Exception(localize(KEY_PASSWORDS_NOT_SAME, DEFAULT_PASSWORDS_NOT_SAME));
        }
        if (newPassword1.length() < MIN_PASSWORD_LENGTH) {
          throw new Exception(localize(KEY_PASSWORD_TOO_SHORT, DEFAULT_PASSWORD_TOO_SHORT));
        }
        for (int i = 0; i < newPassword1.length(); i++) {
          char c = newPassword1.charAt(i);
          boolean isPasswordCharOK = false;
          if ((c >= 'a') && (c <= 'z')) {
            isPasswordCharOK = true;
          } else if ((c >= 'A') && (c <= 'Z')) {
            isPasswordCharOK = true;
          } else if ((c >= '0') && (c <= '9')) {
            isPasswordCharOK = true;
          } else if ((c == 'Å’') || (c == 'Å ') || (c == 'Å¡')) {
            isPasswordCharOK = true;
          } else if ((c == '?') || (c == '€') || (c == '…')) {
            isPasswordCharOK = true;
          }
          if (!isPasswordCharOK) {
            throw new Exception(localize(KEY_PASSWORD_CHAR_ILLEGAL, DEFAULT_PASSWORD_CHAR_ILLEGAL));
          }
        }
        updatePassword = true;
      }
    } catch (Exception e) {
      errorMessage = e.getMessage();
    }

    if (errorMessage != null) {
      add(getErrorText(" " + errorMessage));
    } else {
      // Ok to update preferences
      // UserBusiness ub = (UserBusiness) IBOLookup.getServiceInstance(iwc, UserBusiness.class);

      if (updatePassword) {
        LoginDBHandler.updateLogin(
            ((Integer) user.getPrimaryKey()).intValue(), login, newPassword1);
      }
    }
    drawForm(iwc);
    if (errorMessage == null) {
      add(new Break());
      add(getLocalizedText(KEY_PREFERENCES_SAVED, DEFAULT_PREFERENCES_SAVED));
    }
  }
  private void drawForm(IWContext iwc) {
    Form form = new Form();
    Table T = new Table();
    T.setCellpadding(2);
    T.setCellspacing(2);
    T.setBorder(0);
    form.add(T);

    Table table = new Table();
    //		table.setWidth(getWidth());
    table.setCellpadding(2);
    table.setCellspacing(2);
    table.setBorder(0);
    T.add(table, 1, 1);
    T.setWidth(2, 1, "20");

    T.setVerticalAlignment(1, 1, Table.VERTICAL_ALIGN_BOTTOM);
    T.setVerticalAlignment(3, 1, Table.VERTICAL_ALIGN_BOTTOM);

    int row = 1;

    String personalID =
        PersonalIDFormatter.format(
            user.getPersonalID(), iwc.getIWMainApplication().getSettings().getApplicationLocale());

    table.add(new Break(2), 1, row);
    table.add(getSmallHeader(localize(KEY_PID, DEFAULT_PID)), 1, row);

    if (user.getPersonalID() != null) {
      table.add(getSmallText(personalID), 2, row);
      table.setVerticalAlignment(1, row, Table.VERTICAL_ALIGN_BOTTOM);
      table.setVerticalAlignment(2, row, Table.VERTICAL_ALIGN_BOTTOM);
    }
    row++;
    table.add(getSmallHeader(localize(KEY_LOGIN, DEFAULT_LOGIN)), 1, row);
    LoginTable loginTable =
        LoginDBHandler.getUserLogin(((Integer) user.getPrimaryKey()).intValue());
    if (loginTable != null) {
      table.add(new HiddenInput(PARAMETER_OLD_LOGIN, loginTable.getUserLogin()), 2, row);
      table.add(getSmallText(loginTable.getUserLogin()), 2, row);
      table.setVerticalAlignment(1, row, Table.VERTICAL_ALIGN_BOTTOM);
      table.setVerticalAlignment(2, row, Table.VERTICAL_ALIGN_BOTTOM);
    }

    String valueCurrentPassword =
        iwc.getParameter(PARAMETER_CURRENT_PASSWORD) != null
            ? iwc.getParameter(PARAMETER_CURRENT_PASSWORD)
            : "";
    String valueNewPassword =
        iwc.getParameter(PARAMETER_NEW_PASSWORD) != null
            ? iwc.getParameter(PARAMETER_NEW_PASSWORD)
            : "";
    String valueNewPasswordRepeated =
        iwc.getParameter(PARAMETER_NEW_PASSWORD_REPEATED) != null
            ? iwc.getParameter(PARAMETER_NEW_PASSWORD_REPEATED)
            : "";

    // Text tLogin = getSmallHeader(localize(KEY_LOGIN, DEFAULT_LOGIN));
    Text tCurrentPassword =
        getSmallHeader(localize(KEY_CURRENT_PASSWORD, DEFAULT_CURRENT_PASSWORD));
    Text tNewPassword = getSmallHeader(localize(KEY_NEW_PASSWORD, DEFAULT_NEW_PASSWORD));
    Text tNewPasswordRepeated =
        getSmallHeader(localize(KEY_NEW_PASSWORD_REPEATED, DEFAULT_NEW_PASSWORD_REPEATED));

    PasswordInput tiCurrentPassword =
        (PasswordInput) getStyledInterface(new PasswordInput(PARAMETER_CURRENT_PASSWORD));
    if (valueCurrentPassword != null) {
      tiCurrentPassword.setValue(valueCurrentPassword);
    }
    PasswordInput tiNewPassword =
        (PasswordInput) getStyledInterface(new PasswordInput(PARAMETER_NEW_PASSWORD));
    if (valueNewPassword != null) {
      tiNewPassword.setValue(valueNewPassword);
    }
    PasswordInput tiNewPasswordRepeated =
        (PasswordInput) getStyledInterface(new PasswordInput(PARAMETER_NEW_PASSWORD_REPEATED));
    if (valueNewPasswordRepeated != null) {
      tiNewPasswordRepeated.setValue(valueNewPasswordRepeated);
    }

    SubmitButton sbUpdate =
        (SubmitButton)
            getStyledInterface(
                new SubmitButton(
                    localize(KEY_UPDATE, DEFAULT_UPDATE), PARAMETER_FORM_SUBMIT, "true"));

    row++;
    table.setHeight(row, 12);

    if (requirePasswordVerification) {
      row++;
      table.add(tCurrentPassword, 1, row);
      table.add(tiCurrentPassword, 2, row);
    }

    row++;
    table.add(tNewPassword, 1, row);
    table.add(tiNewPassword, 2, row);

    row++;
    table.add(tNewPasswordRepeated, 1, row);
    table.add(tiNewPasswordRepeated, 2, row);

    row++;
    table.setHeight(row, 12);

    row++;
    table.mergeCells(1, row, 2, row);
    table.setAlignment(1, row, Table.HORIZONTAL_ALIGN_RIGHT);

    table.add(Text.NON_BREAKING_SPACE, 1, row);
    table.add(sbUpdate, 1, row);

    add(form);
  }
  @SuppressWarnings("unchecked")
  protected void processRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost)
      throws ServletException, IOException {
    ServerManager manager = getServerManager();
    IWMainApplication iwma = IWMainApplication.getIWMainApplication(req);

    // extract the parameters from the request
    ParameterList requestParameters = new ParameterList(req.getParameterMap());

    OpenIDServerBean serverBean = ELUtil.getInstance().getBean("openIDServerBean");
    ParameterList sessionStoredParameterList = serverBean.getParameterList();
    if (sessionStoredParameterList != null) {
      if (!requestParameters.hasParameter(OpenIDConstants.PARAMETER_OPENID_MODE)) {
        sessionStoredParameterList.addParams(requestParameters);
        requestParameters = sessionStoredParameterList;
      }
    }

    String mode =
        requestParameters.hasParameter(OpenIDConstants.PARAMETER_OPENID_MODE)
            ? requestParameters.getParameterValue(OpenIDConstants.PARAMETER_OPENID_MODE)
            : null;
    String realm =
        requestParameters.hasParameter(OpenIDConstants.PARAMETER_REALM)
            ? requestParameters.getParameterValue(OpenIDConstants.PARAMETER_REALM)
            : null;
    if (realm != null) {
      serverBean.setReturnUrl(realm);
      realm = getRealmName(realm);
      serverBean.setRealm(realm);
    }

    Message response;
    String responseText = null;

    try {
      if (OpenIDConstants.PARAMETER_ASSOCIATE.equals(mode)) {
        // --- process an association request ---
        response = manager.associationResponse(requestParameters);
        responseText = response.keyValueFormEncoding();
      } else if (OpenIDConstants.PARAMETER_CHECKID_SETUP.equals(mode)
          || OpenIDConstants.PARAMETER_CHECKID_IMMEDIATE.equals(mode)) {
        IWContext iwc = new IWContext(req, resp, getServletContext());

        boolean goToLogin = doRedirectToLoginPage(manager, requestParameters, iwc, realm);

        if (!goToLogin) {
          serverBean.setParameterList(null);
          serverBean.setServerUrl(null);
          serverBean.setDoRedirect(null);
          serverBean.setUsername(null);

          // interact with the user and obtain data needed to continue
          User user = iwc.getCurrentUser();
          String userSelectedClaimedId = getUserSelectedClaimedId(iwc, user);

          // --- process an authentication request ---
          AuthRequest authReq =
              AuthRequest.createAuthRequest(requestParameters, manager.getRealmVerifier());

          storeRequestedAttributesToSession(iwc, authReq);

          Boolean authenticatedAndApproved = isAuthenticatedAndApproved(iwc, user, authReq);

          String opLocalId = null;
          // if the user chose a different claimed_id than the one in request
          if (userSelectedClaimedId != null
              && !userSelectedClaimedId.equals(authReq.getClaimed())) {
            opLocalId = userSelectedClaimedId;
          }

          response =
              manager.authResponse(
                  requestParameters,
                  opLocalId,
                  userSelectedClaimedId,
                  authenticatedAndApproved.booleanValue(),
                  false); // Sign after we added extensions.

          if (response instanceof DirectError) {
            directResponse(resp, response.keyValueFormEncoding());
            return;
          } else if (response instanceof AuthFailure) {
            redirectToAuthorisationPage(req, resp, requestParameters, serverBean);
            return;
          } else {
            String[] extensionsToSign = prepareResponse(serverBean, response, iwc, user, authReq);
            boolean signExtensions =
                iwma.getSettings().getBoolean(OpenIDConstants.PROPERTY_SIGN_EXTENSIONS, false);

            AuthSuccess success = (AuthSuccess) response;
            if (signExtensions) {
              success.setSignExtensions(extensionsToSign);
            }

            // Sign the auth success message.
            // This is required as AuthSuccess.buildSignedList has a `todo' tag now.
            manager.sign(success);

            // caller will need to decide which of the following to use:

            // option1: GET HTTP-redirect to the return_to URL
            //		                cleanUpBeforeReturning(iwc, loginExpireHandle);
            // Clean up before returning
            serverBean.invalidate();

            getDAO().createLogEntry(user.getUniqueId(), realm, "");

            resp.sendRedirect(response.getDestinationUrl(true));
            return;

            // option2: HTML FORM Redirection
            // RequestDispatcher dispatcher =
            // getServletContext().getRequestDispatcher("formredirection.jsp");
            // httpReq.setAttribute("parameterMap", response.getParameterMap());
            // httpReq.setAttribute("destinationUrl", response.getDestinationUrl(false));
            // dispatcher.forward(request, response);
            // return null;
          }
        } else {
          redirectToLoginPage(req, resp, requestParameters, serverBean, manager);
          return;
        }
      } else if (OpenIDConstants.PARAMETER_CHECK_AUTHENTICATION.equals(mode)) {
        // --- processing a verification request ---
        response = manager.verify(requestParameters);
        responseText = response.keyValueFormEncoding();
      } else {
        // --- error response ---
        response = DirectError.createDirectError("Unknown request");
        responseText = response.keyValueFormEncoding();
        serverBean.invalidate();
      }
    } catch (MessageException me) {
      me.printStackTrace();
      responseText = me.getMessage();
      serverBean.invalidate();
    } catch (AssociationException ae) {
      ae.printStackTrace();
      responseText = ae.getMessage();
      serverBean.invalidate();
    } catch (ServerException se) {
      se.printStackTrace();
      responseText = se.getMessage();
      serverBean.invalidate();
    }

    // return the result to the user
    directResponse(resp, responseText);
  }
  /**
   * 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;
  }
  /* (non-Javadoc)
   * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
   */
  public int compare(User user1, User user2) {
    Name name1 = new Name(user1.getFirstName(), user1.getMiddleName(), user1.getLastName());
    Name name2 = new Name(user2.getFirstName(), user2.getMiddleName(), user2.getLastName());

    return collator.compare(name1.getName(iLocale), name2.getName(iLocale));
  }
  private Table getPlacementTable(IWContext iwc) throws RemoteException {
    Table table = new Table();
    // table.setColor("#DDDDDD");
    table.setBorder(0);
    table.setWidth(Table.HUNDRED_PERCENT);
    table.setCellpadding(1);
    table.setCellspacing(2);
    int col = 1;
    int row = 1;

    // *** HEADING Placements ***
    Text pupilTxt = new Text(localize(KEY_PLACEMENTS_HEADING, "Placements"));
    pupilTxt.setFontStyle(STYLE_UNDERLINED_SMALL_HEADER);
    table.add(pupilTxt, col++, row);
    table.setRowHeight(row, "40");
    table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM);
    table.mergeCells(col, row, table.getColumns(), row);
    col = 1;
    row++;

    // empty space row
    table.add(this.transGIF, col, row);
    table.setRowHeight(row, "10");
    col = 1;
    row++;

    //  *** Column headings ***
    table.add(getLocalizedSmallHeader(KEY_NUMBER, "No."), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
    table.add(getLocalizedSmallHeader(KEY_SCHOOL_TYPE, "School type"), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
    table.add(getLocalizedSmallHeader(KEY_PROVIDER, "Provider"), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
    table.add(getLocalizedSmallHeader(KEY_SCHOOL_YEAR, "School year"), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
    table.add(getLocalizedSmallHeader(KEY_STUDY_PATH, "Study path"), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
    table.add(getLocalizedSmallHeader(KEY_SCHOOL_GROUP, "School group"), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
    table.add(getLocalizedSmallHeader(KEY_START_DATE, "Start date"), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
    table.add(getLocalizedSmallHeader(KEY_END_DATE, "End date"), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
    table.add(getLocalizedSmallHeader(KEY_REGISTRATOR, "Registrator"), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
    table.add(getLocalizedSmallHeader(KEY_REGISTRATION_CREATED_DATE, "Created date"), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
    table.add(getLocalizedSmallHeader(KEY_PLACEMENT_PARAGRAPH_SHORT, "Par"), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
    table.add(getLocalizedSmallHeader(KEY_NOTES, "Notes"), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
    table.add(Text.getNonBrakingSpace(), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
    table.add(Text.getNonBrakingSpace(), col, row);
    table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);

    table.setRowColor(row, getHeaderColor());

    table.setRowHeight(row, "18");
    row++;

    // Loop placements
    Collection placements = null;
    try {
      if (this.pupil != null) {
        placements =
            getSchoolBusiness(iwc)
                .getSchoolClassMemberHome()
                .findAllOrderedByRegisterDate(this.pupil);
      }
    } catch (FinderException e) {
    }

    if (placements != null && placements.size() > 0) {
      int zebra = 0;
      int rowNum = 0;
      table.add(new HiddenInput(PARAM_REMOVE_PLACEMENT, "-1"), 1, 1);
      for (Iterator iter = placements.iterator(); iter.hasNext(); ) {
        rowNum++;
        SchoolClassMember plc = (SchoolClassMember) iter.next();
        col = 1;

        // Row number
        table.add(getSmallText(String.valueOf(rowNum)), col++, row);
        // School type
        try {
          table.add(getSmallText(plc.getSchoolType().getName()), col++, row);
        } catch (Exception e) {
          col++;
        }
        // Provider
        try {
          table.add(getSmallText(plc.getSchoolClass().getSchool().getName()), col++, row);
        } catch (Exception e) {
          col++;
        }
        // School year
        try {
          table.add(getSmallText(plc.getSchoolYear().getName()), col++, row);
        } catch (Exception e) {
          col++;
        }
        // Study path
        try {
          if (plc.getStudyPathId() != -1) {
            SchoolStudyPathHome home =
                (SchoolStudyPathHome) IDOLookup.getHome(SchoolStudyPath.class);
            SchoolStudyPath sp = home.findByPrimaryKey(new Integer(plc.getStudyPathId()));
            table.add(getSmallText(sp.getCode()), col, row);
          }
        } catch (Exception e) {
        }
        col++;
        // School type
        try {
          table.add(getSmallText(plc.getSchoolClass().getSchoolClassName()), col++, row);
        } catch (Exception e) {
          col++;
        }
        // Start date
        try {
          String dateStr =
              getCentralPlacementBusiness(iwc).getDateString(plc.getRegisterDate(), "yyyy-MM-dd");
          table.add(getSmallText(dateStr), col++, row);
        } catch (Exception e) {
          col++;
        }
        // End date
        try {
          String dateStr =
              getCentralPlacementBusiness(iwc).getDateString(plc.getRemovedDate(), "yyyy-MM-dd");
          table.add(getSmallText(dateStr), col++, row);
        } catch (Exception e) {
          col++;
        }
        // Registrator
        try {
          int registratorID = plc.getRegistratorId();
          User registrator = getUserBusiness(iwc).getUser(registratorID);
          if (registrator != null) {
            Name name =
                new Name(
                    registrator.getFirstName(),
                    registrator.getMiddleName(),
                    registrator.getLastName());
            table.add(
                getSmallText(name.getName(iwc.getApplicationSettings().getDefaultLocale(), false)),
                col++,
                row);
          }
        } catch (Exception e) {
          col++;
        }
        // Created date
        try {
          String dateStr =
              getCentralPlacementBusiness(iwc)
                  .getDateString(plc.getRegistrationCreatedDate(), "yyyy-MM-dd");
          table.add(getSmallText(dateStr), col++, row);
        } catch (Exception e) {
          col++;
        }
        // Placement paragraph
        try {
          if (plc.getPlacementParagraph() != null) {
            table.add(getSmallText(plc.getPlacementParagraph()), col++, row);
          } else {
            col++;
          }
        } catch (Exception e) {
          col++;
        }
        // Notes
        try {
          if (plc.getNotes() != null) {
            table.add(getSmallText(plc.getNotes()), col++, row);
          } else {
            col++;
          }
        } catch (Exception e) {
          col++;
        }
        // Pupil overview button
        try {
          // Get Pupil overview button
          String plcId = ((Integer) plc.getPrimaryKey()).toString();
          String schClassId = String.valueOf(plc.getSchoolClassId());

          Link editButt =
              new Link(this.getEditIcon(localize(KEY_TOOLTIP_PUPIL_OVERVIEW, "Pupil overview")));
          editButt.setWindowToOpen(PlacementHistoryEditPlacement.class);
          editButt.setParameter(
              SchoolAdminOverview.PARAMETER_METHOD,
              String.valueOf(SchoolAdminOverview.METHOD_OVERVIEW));
          editButt.addParameter(
              SchoolAdminOverview.PARAMETER_METHOD,
              String.valueOf(SchoolAdminOverview.METHOD_OVERVIEW));
          editButt.addParameter(SchoolAdminOverview.PARAMETER_SHOW_ONLY_OVERVIEW, "true");
          editButt.addParameter(SchoolAdminOverview.PARAMETER_SHOW_NO_CHOICES, "true");
          editButt.addParameter(SchoolAdminOverview.PARAMETER_PAGE_ID, getParentPage().getPageID());
          editButt.addParameter(
              SchoolAdminOverview.PARAMETER_USER_ID, String.valueOf(plc.getClassMemberId()));
          editButt.addParameter(SchoolAdminOverview.PARAMETER_SCHOOL_CLASS_ID, schClassId);
          editButt.addParameter(SchoolAdminOverview.PARAMETER_SCHOOL_CLASS_MEMBER_ID, plcId);
          editButt.addParameter(
              SchoolAdminOverview.PARAMETER_RESOURCE_PERMISSION,
              SchoolAdminOverview.PARAMETER_RESOURCE_PERM_VALUE_CENTRAL_ADMIN);
          editButt.addParameter(
              SchoolAdminOverview.PARAMETER_FROM_CENTRAL_PLACEMENT_EDITOR, "true");
          if (plc.getRemovedDate() != null) {
            editButt.addParameter(
                SchoolAdminOverview.PARAMETER_SCHOOL_CLASS_MEMBER_REMOVED_DATE,
                plc.getRemovedDate().toString());
          }

          table.add(editButt, col, row);
          table.setAlignment(col++, row, Table.HORIZONTAL_ALIGN_CENTER);
        } catch (Exception e) {
          col++;
        }
        // Remove button
        try {
          // Get remove button
          Image delImg = getDeleteIcon(localize(KEY_TOOLTIP_REMOVE_PLC, "Delete placement"));
          int plcID = ((Integer) plc.getPrimaryKey()).intValue();

          SubmitButton delButt = new SubmitButton(delImg);
          delButt.setValueOnClick(PARAM_REMOVE_PLACEMENT, String.valueOf(plcID));
          delButt.setSubmitConfirm(
              localize(
                  KEY_CONFIRM_REMOVE_PLC_MSG,
                  "Do you really want to erase this school placement and its resource placements?"));
          delButt.setToolTip(localize(KEY_TOOLTIP_REMOVE_PLC, "Delete school placement"));
          table.add(delButt, col, row);
          table.setAlignment(col, row, Table.HORIZONTAL_ALIGN_CENTER);
        } catch (Exception e) {
        }

        String zebraColor = zebra % 2 == 0 ? getZebraColor2() : getZebraColor1();
        table.setRowColor(row, zebraColor);
        col = 2;
        row++;

        // Resources
        String rscStr = getResourceBusiness(iwc).getResourcesStringXtraInfo(plc);
        if (!("".equals(rscStr))) {
          table.add(
              getSmallText("<i>" + localize(KEY_RESOURCES, "Resources") + ":</i> "), col, row);
          table.add(getSmallText("<i>" + rscStr + "</i>"), col, row);
          table.setRowColor(row, zebraColor);
          table.mergeCells(col, row, table.getColumns(), row);
          row++;
        }

        zebra++;
      }
    }

    col = 1;

    // empty space row
    table.add(this.transGIF, col, row);
    table.setRowHeight(row, "20");

    return table;
  }
  /*
   * (non-Javadoc)
   *
   * @see is.idega.idegaweb.member.presentation.UserEditor#presentateUserRelations(com.idega.presentation.IWContext)
   */
  protected void presentUserRelations(IWContext iwc) throws RemoteException {
    Table relationsTable = new Table();
    relationsTable.setCellspacing(4);
    relationsTable.setWidth(Table.HUNDRED_PERCENT);
    int row = 1;

    if (user != null) {
      addSeperator(iwrb.getLocalizedString("mbe.user_relations", "User relations"));
      CommuneFamilyService familyService = getFamilyService(iwc);

      // parent handling
      relationsTable.add(getHeader(iwrb.getLocalizedString("mbe.parents", "Parents")), 1, row++);
      Collection parents = null;
      try {
        parents = familyService.getParentsFor(user);
        if (parents != null && !parents.isEmpty()) {
          for (Iterator iter = parents.iterator(); iter.hasNext(); ) {
            User parent = (User) iter.next();
            relationsTable.add(getRelatedUserLink(parent), 1, row);
            relationsTable.add(
                PersonalIDFormatter.format(parent.getPersonalID(), iwc.getCurrentLocale()),
                2,
                row++);
          }
        }
      } catch (Exception e1) {
      }
      row++;

      // partner handling
      relationsTable.add(getHeader(iwrb.getLocalizedString("mbe.spouse", "Spouse")), 1, row++);
      User partner = null;
      try {
        partner = familyService.getSpouseFor(this.user);
      } catch (NoSpouseFound e) {
      } catch (Exception e) {
      }
      if (partner != null) {
        relationsTable.add(getRelatedUserLink(partner), 1, row);
        relationsTable.add(
            PersonalIDFormatter.format(partner.getPersonalID(), iwc.getCurrentLocale()), 2, row++);
      }
      row++;

      // cohabitant handling
      relationsTable.add(
          getHeader(iwrb.getLocalizedString("mbe.cohabitant", "Cohabitant")), 1, row++);
      User cohabitant = null;
      try {
        cohabitant = familyService.getCohabitantFor(this.user);
      } catch (NoCohabitantFound e) {
      }
      if (cohabitant != null) {
        relationsTable.add(getRelatedUserLink(cohabitant), 1, row);
        relationsTable.add(
            PersonalIDFormatter.format(cohabitant.getPersonalID(), iwc.getCurrentLocale()),
            2,
            row++);
      }
      row++;

      // biological children handling
      relationsTable.add(
          getHeader(iwrb.getLocalizedString("mbe.parential_children", "Parential children")),
          1,
          row++);
      Collection children = null;
      Collection custodianChildren = null;
      Text star = new Text(" *");
      star.setStyleClass(STYLENAME_HEADER);
      try {
        children = familyService.getChildrenFor(user);
        custodianChildren = familyService.getChildrenInCustodyOf(user);
        if (custodianChildren != null && !custodianChildren.isEmpty()) {
          for (Iterator iter = custodianChildren.iterator(); iter.hasNext(); ) {
            User child = (User) iter.next();
            relationsTable.add(getRelatedUserLink(child), 1, row);
            if (children != null && !children.contains(child)) {
              relationsTable.add(star, 1, row);
            }
            relationsTable.add(
                PersonalIDFormatter.format(child.getPersonalID(), iwc.getCurrentLocale()),
                2,
                row++);
            row++;
          }
        }
      } catch (Exception e2) {
      }
    }
    relationsTable.setWidth(1, "300");
    row++;

    Text infoText =
        new Text(
            iwrb.getLocalizedString(
                "person_is_only_custodian", "* Not child, person is only custodian"));
    infoText.setStyleClass(STYLENAME_TEXT);
    relationsTable.add(infoText, 1, row++);
    row++;

    relationsTable.setAlignment(2, row, Table.HORIZONTAL_ALIGN_RIGHT);
    relationsTable.add(getEditButton(iwc, ACTION_EDIT_RELATIONS), 2, row);

    addToMainPart(relationsTable);
  }
  /*
   * (non-Javadoc)
   *
   * @see is.idega.idegaweb.member.presentation.UserEditor#presentateUserRelations(com.idega.presentation.IWContext)
   */
  protected void editUserRelations(IWContext iwc) throws RemoteException {
    Table relationsTable = new Table();
    relationsTable.setWidth(Table.HUNDRED_PERCENT);
    relationsTable.setCellspacing(4);
    int row = 1;

    if (user != null) {
      addSeperator(iwrb.getLocalizedString("mbe.user_relations", "User relations"));
      CommuneFamilyService familyService = getFamilyService(iwc);
      // partner handling
      relationsTable.add(getHeader(iwrb.getLocalizedString("mbe.spouse", "Spouse")), 1, row);
      User partner = null;
      try {
        partner = familyService.getSpouseFor(this.user);
      } catch (NoSpouseFound e) {
      } catch (Exception e) {
      }
      if (partner != null) {
        relationsTable.add(getRelatedUserLink(partner), 2, row);
        relationsTable.add(
            getDisconnectorLink(
                familyService.getSpouseRelationType(),
                null,
                (Integer) user.getPrimaryKey(),
                (Integer) partner.getPrimaryKey(),
                getDeleteIcon(
                    iwrb.getLocalizedString(
                        "mbe.remove_spouse_relation", "Remove spouse relationship"))),
            3,
            row);
      }

      // cohabitant handling
      relationsTable.add(
          getHeader(iwrb.getLocalizedString("mbe.cohabitant", "Cohabitant")), 5, row);
      User cohabitant = null;
      try {
        cohabitant = familyService.getCohabitantFor(this.user);
      } catch (NoCohabitantFound e) {
      }
      if (cohabitant != null) {
        relationsTable.add(getRelatedUserLink(cohabitant), 6, row);
        relationsTable.add(
            getDisconnectorLink(
                familyService.getCohabitantRelationType(),
                null,
                (Integer) user.getPrimaryKey(),
                (Integer) cohabitant.getPrimaryKey(),
                getDeleteIcon(
                    iwrb.getLocalizedString(
                        "mbe.remove_cohabitant_relation", "Remove cohabitant relationship"))),
            7,
            row);
      }
      row++;

      // parent handling
      int parentStartRow = row, custodianStartRow = row;
      relationsTable.add(getHeader(iwrb.getLocalizedString("mbe.parents", "Parents")), 1, row);
      Collection parents = null;
      try {
        parents = familyService.getParentsFor(user);
        if (parents != null && !parents.isEmpty()) {
          for (Iterator iter = parents.iterator(); iter.hasNext(); ) {
            User parent = (User) iter.next();
            relationsTable.add(getRelatedUserLink(parent), 2, parentStartRow);
            String relationType = familyService.getParentRelationType();
            relationsTable.add(
                getDisconnectorLink(
                    null,
                    relationType,
                    (Integer) user.getPrimaryKey(),
                    (Integer) parent.getPrimaryKey(),
                    getDeleteIcon(
                        iwrb.getLocalizedString(
                            "mbe.remove_parent_relation", "Remove parent relationship"))),
                3,
                parentStartRow);
            parentStartRow++;
          }
        }
      } catch (Exception e1) {
      }

      // custodians handling
      relationsTable.add(
          getHeader(iwrb.getLocalizedString("mbe.custodians", "Custodians")), 5, custodianStartRow);
      Collection custodians = null;
      try {
        custodians = familyService.getCustodiansFor(user, false);
        if (custodians != null && !custodians.isEmpty()) {
          for (Iterator iter = custodians.iterator(); iter.hasNext(); ) {
            User custodian = (User) iter.next();
            relationsTable.add(getRelatedUserLink(custodian), 6, custodianStartRow);
            String relationType = familyService.getCustodianRelationType();
            relationsTable.add(
                getDisconnectorLink(
                    null,
                    relationType,
                    (Integer) user.getPrimaryKey(),
                    (Integer) custodian.getPrimaryKey(),
                    getDeleteIcon(
                        iwrb.getLocalizedString(
                            "mbe.remove_custodian_relation", "Remove custodian relationship"))),
                7,
                custodianStartRow);
            custodianStartRow++;
          }
        }
      } catch (Exception e1) {
      }
      row = Math.max(custodianStartRow, parentStartRow) + 1;

      // biological children handling
      relationsTable.add(
          getHeader(iwrb.getLocalizedString("mbe.parential_children", "Parential children")),
          1,
          row);
      Collection children = null;
      int childrowstart = row;
      try {
        children = familyService.getChildrenFor(user);
        if (children != null && !children.isEmpty()) {
          for (Iterator iter = children.iterator(); iter.hasNext(); ) {
            User child = (User) iter.next();
            relationsTable.add(getRelatedUserLink(child), 2, row);
            relationsTable.add(
                getDisconnectorLink(
                    familyService.getParentRelationType(),
                    null,
                    (Integer) user.getPrimaryKey(),
                    (Integer) child.getPrimaryKey(),
                    getDeleteIcon(
                        iwrb.getLocalizedString(
                            "mbe.remove_child_relation", "Remove child relationship"))),
                3,
                row);
            row++;
          }
        }
      } catch (Exception e2) {
      }
      // custody children handling
      row = childrowstart;
      relationsTable.add(
          getHeader(iwrb.getLocalizedString("mbe.custody_children", "Custody children")), 5, row);
      try {
        children = familyService.getChildrenInCustodyOf(user);
        if (children != null && !children.isEmpty()) {
          for (Iterator iter = children.iterator(); iter.hasNext(); ) {
            User child = (User) iter.next();
            relationsTable.add(getRelatedUserLink(child), 6, row);
            relationsTable.add(
                getDisconnectorLink(
                    familyService.getCustodianRelationType(),
                    null,
                    (Integer) user.getPrimaryKey(),
                    (Integer) child.getPrimaryKey(),
                    getDeleteIcon(
                        iwrb.getLocalizedString(
                            "mbe.remove_child_relation", "Remove child relationship"))),
                7,
                row);
            row++;
          }
        }
      } catch (NoChildrenFound e3) {
        // e3.printStackTrace();
      } catch (RemoteException e3) {
        e3.printStackTrace();
      } catch (EJBException e3) {
        e3.printStackTrace();
      }
    }
    relationsTable.setWidth(2, "150");
    relationsTable.setWidth(6, "150");

    row++;
    relationsTable.mergeCells(1, row, relationsTable.getColumns(), row);
    relationsTable.setAlignment(1, row, Table.HORIZONTAL_ALIGN_RIGHT);
    relationsTable.add(getCancelButton(iwc), 1, row);

    addToMainPart(relationsTable);

    presentButtons(iwc);
    presentButtonRegister(iwc);
  }
  /** 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;
  }
  @SuppressWarnings("unchecked")
  private void storeRequestedAttributesToSession(IWContext iwc, AuthRequest authReq) {
    if (authReq.hasExtension(AxMessage.OPENID_NS_AX)) {
      MessageExtension ext;
      try {
        ext = authReq.getExtension(AxMessage.OPENID_NS_AX);
        if (ext instanceof FetchRequest) {
          FetchRequest fetchReq = (FetchRequest) ext;
          OpenIDServerBean serverBean = ELUtil.getInstance().getBean("openIDServerBean");
          Map<String, String> allAttributes = (Map<String, String>) fetchReq.getAttributes();
          Map<String, String> required = (Map<String, String>) fetchReq.getAttributes(true);

          List<AuthorizedAttribute> allAttributesList = new ArrayList<AuthorizedAttribute>();
          List<AuthorizedAttribute> requiredAttributesList = new ArrayList<AuthorizedAttribute>();
          List<AuthorizedAttribute> optionalAttributesList = new ArrayList<AuthorizedAttribute>();

          String realm = serverBean.getRealm();

          for (String alias : allAttributes.keySet()) {
            ExchangeAttribute attribute =
                getDAO().getExchangeAttribute(alias, allAttributes.get(alias));
            if (attribute != null) {
              User user = iwc.getCurrentUser();
              AuthorizedAttribute aattr =
                  getDAO().getAuthorizedAttributes(user.getUniqueId(), realm, attribute);
              if (aattr == null) {
                aattr = new AuthorizedAttribute();
                aattr.setExchangeAttribute(attribute);
                aattr.setRealm(realm);
                aattr.setUserUUID(user.getUniqueId());
                aattr.setIsAllowed(true);
              }
              allAttributesList.add(aattr);
              if (required.containsKey(alias) && attribute.getType().equals(required.get(alias))) {
                requiredAttributesList.add(aattr);
              } else {
                optionalAttributesList.add(aattr);
              }
            } else {
              LOGGER.warning(
                  "Requesting unknown exchange attribute: "
                      + alias
                      + " : "
                      + allAttributes.get(alias));
              // throw new UnsupportedOperationException("Requesting unknown exchange attribute.");
            }
          }

          serverBean.setRequestedAttributes(allAttributesList);
          serverBean.setRequiredAttributes(requiredAttributesList);
          serverBean.setOptionalAttributes(optionalAttributesList);
          return;
        } else /*if (ext instanceof StoreRequest)*/ {
          // TODO implement?
          throw new UnsupportedOperationException("TODO");
        }
      } catch (MessageException e) {
        e.printStackTrace();
      }
    }
    if (authReq.hasExtension(SRegMessage.OPENID_NS_SREG11)) {
      try {
        MessageExtension ext = authReq.getExtension(SRegMessage.OPENID_NS_SREG11);

        if (ext instanceof SRegRequest) {
          SRegRequest sregReq = (SRegRequest) ext;
          List<String> all = sregReq.getAttributes();
          List<String> required = sregReq.getAttributes(true);
          List<String> optional = sregReq.getAttributes(false);

          List<AuthorizedAttribute> allAttributesList = new ArrayList<AuthorizedAttribute>();
          List<AuthorizedAttribute> requiredAttributesList = new ArrayList<AuthorizedAttribute>();
          List<AuthorizedAttribute> optionalAttributesList = new ArrayList<AuthorizedAttribute>();

          OpenIDServerBean serverBean = ELUtil.getInstance().getBean("openIDServerBean");
          String realm = serverBean.getRealm();
          User user = iwc.getCurrentUser();

          for (String alias : all) {
            ExchangeAttribute attribute = getDAO().getExchangeAttribute(alias);
            if (attribute != null) {
              AuthorizedAttribute aattr =
                  getDAO().getAuthorizedAttributes(user.getUniqueId(), realm, attribute);
              if (aattr == null) {
                aattr = new AuthorizedAttribute();
                aattr.setExchangeAttribute(attribute);
                aattr.setRealm(realm);
                aattr.setUserUUID(user.getUniqueId());
                aattr.setIsAllowed(true);
              }
              allAttributesList.add(aattr);
              if (required.contains(alias)) {
                requiredAttributesList.add(aattr);
              }
              if (optional.contains(alias)) {
                optionalAttributesList.add(aattr);
              }
            }
          }

          serverBean.setRequestedAttributes(allAttributesList);
          serverBean.setRequiredAttributes(requiredAttributesList);
          serverBean.setOptionalAttributes(optionalAttributesList);
          return;
        }
      } catch (MessageException e) {
        e.printStackTrace();
      }
    }
  }
 /*
  * (non-Javadoc)
  *
  * @see is.idega.idegaweb.member.presentation.UserEditor#isAllowPersonalIdEdit(com.idega.user.data.User)
  */
 public boolean isAllowPersonalIdEdit(User user) {
   if (user != null && user.getPersonalID() != null) {
     if (user.getPersonalID().indexOf("TF") != -1) return true;
   }
   return false;
 }
  public String getPlacementString(SchoolClassMember placement, User user, IWResourceBundle iwrb) {
    // Placement
    StringBuffer buf = new StringBuffer("");
    try {
      // add school name
      buf.append(placement.getSchoolClass().getSchool().getName());
    } catch (Exception e) {
    }
    try {
      // school year
      SchoolYear theYear = placement.getSchoolYear();
      if (theYear != null) {
        buf.append(
            ", "
                + iwrb.getLocalizedString(
                    CentralPlacementEditorConstants.KEY_SCHOOL_YEAR, "school year")
                + " "
                + theYear.getName());
      }
    } catch (Exception e) {
    }
    try {
      // add school group
      buf.append(
          ", "
              + iwrb.getLocalizedString(CentralPlacementEditorConstants.KEY_SCHOOL_GROUP, "group")
              + " "
              + placement.getSchoolClass().getSchoolClassName());
    } catch (Exception e) {
    }
    try {
      // add study path
      if (placement.getStudyPathId() != -1) {
        SchoolStudyPathHome home = (SchoolStudyPathHome) IDOLookup.getHome(SchoolStudyPath.class);
        SchoolStudyPath sp = home.findByPrimaryKey(new Integer(placement.getStudyPathId()));
        buf.append(
            ", "
                + iwrb.getLocalizedString(
                    CentralPlacementEditorConstants.KEY_STUDY_PATH, "Study path")
                + " "
                + sp.getCode());
      }
    } catch (Exception e) {
    }

    try {
      // add language
      if (placement.getLanguage() != null && !("-1").equals(placement.getLanguage())) {
        buf.append(
            ", "
                + iwrb.getLocalizedString(CentralPlacementEditorConstants.KEY_LANGUAGE, "Language")
                + " "
                + iwrb.getLocalizedString(placement.getLanguage(), ""));
      }
    } catch (Exception e) {
    }

    try {
      // add native language
      if (user.getNativeLanguage() != null) {
        buf.append(
            ", "
                + iwrb.getLocalizedString(
                    CentralPlacementEditorConstants.KEY_NATIVE_LANGUAGE, "Native language")
                + " "
                + user.getNativeLanguage());
      }
    } catch (Exception e) {
    }
    return buf.toString();
  }
  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;
  }
  protected String getAttributeValue(IWContext iwc, User user, String alias, String type) {
    if (OpenIDConstants.ATTRIBUTE_ALIAS_EMAIL.equals(alias)
        || OpenIDConstants.ATTRIBUTE_TYPE_EMAIL.equals(type)) {
      Email email = null;
      try {
        email = getUserBusiness(iwc).getUsersMainEmail(user);
      } catch (NoEmailFoundException e) {
        /*No action...*/
      } catch (RemoteException e) {
        e.printStackTrace();
      }

      return (email != null ? email.getEmailAddress() : "");
    } else if (OpenIDConstants.ATTRIBUTE_ALIAS_PERSONAL_ID.equals(alias)
        || OpenIDConstants.ATTRIBUTE_TYPE_PERSONAL_ID.equals(type)) {
      return (user.getPersonalID() != null ? user.getPersonalID() : "");
    } else if (OpenIDConstants.ATTRIBUTE_ALIAS_FULL_NAME.equals(alias)
        || OpenIDConstants.ATTRIBUTE_TYPE_FULL_NAME.equals(type)) {
      return user.getName();
    } else if (OpenIDConstants.ATTRIBUTE_ALIAS_DATE_OF_BIRTH.equals(alias)
        || OpenIDConstants.ATTRIBUTE_TYPE_DATE_OF_BIRTH.equals(type)) {
      return (user.getDateOfBirth() != null
          ? new IWTimestamp(user.getDateOfBirth()).toSQLDateString()
          : "");
    } else if (OpenIDConstants.ATTRIBUTE_ALIAS_GENDER.equals(alias)
        || OpenIDConstants.ATTRIBUTE_TYPE_GENDER.equals(type)) {
      return (user.getGender() != null ? (user.getGender().isMaleGender() ? "M" : "F") : "");
    } else if (OpenIDConstants.ATTRIBUTE_ALIAS_NICKNAME.equals(alias)
        || OpenIDConstants.ATTRIBUTE_TYPE_FRIENDLY_NAME.equals(type)) {
      return LoginDBHandler.getUserLogin(user).getUserLogin();
    } else if (OpenIDConstants.ATTRIBUTE_ALIAS_POSTCODE.equals(alias)
        || OpenIDConstants.ATTRIBUTE_TYPE_POSTAL_CODE.equals(type)) {
      try {
        Address address = getUserBusiness(iwc).getUsersMainAddress(user);
        if (address != null) {
          PostalCode postal = address.getPostalCode();
          return postal != null ? postal.getPostalCode() : "";
        }
      } catch (RemoteException re) {
        re.printStackTrace();
      }
    } else if (OpenIDConstants.ATTRIBUTE_ALIAS_COUNTRY.equals(alias)
        || OpenIDConstants.ATTRIBUTE_TYPE_COUNTRY.equals(type)) {
      try {
        Address address = getUserBusiness(iwc).getUsersMainAddress(user);
        if (address != null) {
          return address.getCountry().getIsoAbbreviation();
        }
      } catch (RemoteException re) {
        re.printStackTrace();
      }
    } else if (OpenIDConstants.ATTRIBUTE_ALIAS_LANGUAGE.equals(alias)
        || OpenIDConstants.ATTRIBUTE_TYPE_LANGUAGE.equals(type)) {
      if (user.getPreferredLocale() != null) {
        Locale locale = LocaleUtil.getLocale(user.getPreferredLocale());
        return locale.getLanguage() + "-" + locale.getCountry();
      } else {
        try {
          Address address = getUserBusiness(iwc).getUsersMainAddress(user);
          if (address != null) {
            Country country = address.getCountry();
            return country.getIsoAbbreviation().toLowerCase() + "-" + country.getIsoAbbreviation();
          }
        } catch (RemoteException re) {
          re.printStackTrace();
        }
      }
    } else if (OpenIDConstants.ATTRIBUTE_ALIAS_TIMEZONE.equals(alias)
        || OpenIDConstants.ATTRIBUTE_TYPE_TIMEZONE.equals(type)) {
      try {
        Address address = getUserBusiness(iwc).getUsersMainAddress(user);
        if (address != null) {
          Country country = address.getCountry();
          Locale locale =
              new Locale(country.getIsoAbbreviation().toLowerCase(), country.getIsoAbbreviation());
          Calendar calendar = new GregorianCalendar(locale);

          return calendar.getTimeZone().getDisplayName(Locale.ENGLISH);
        }
      } catch (RemoteException re) {
        re.printStackTrace();
      }
    }

    return "";
  }