001    /***************************************************************************************************
002     *               MODULE DESCRIPTION
003     ****************************************************************************************************
004     *
005     *               NAME:           ContactPerson.java
006     *               LANGUAGE:       Java2
007     *               DATE:           27.3.2003
008     *               AUTHOR:         Miika Nurminen, University of Jyväskylä
009     *
010     ****************************************************************************************************
011     *               COPYRIGHT (C) KIURU -PROJECT GROUP
012     *               Limited rights granted. Please refer to license
013     ****************************************************************************************************
014     *  
015     ****************************************************************************************************
016     *               UPDATES
017     ****************************************************************************************************
018     *
019     *   27.3.2003: Initial release / mn
020     *
021     ****************************************************************************************************/
022    package kiurubeans;
023    import kotkabeans.UseModule;
024    import kotkabeans.RS2;
025    import kotkabeans.DB;
026    import kotkabeans.AutoNumber;
027    import java.sql.PreparedStatement;
028    import javax.servlet.http.HttpServletRequest;
029    
030    
031    /**
032     * Representation of a contact person.
033     * 
034     * @author Miika Nurminen
035     */
036    public class ContactPerson extends EntityHandler {
037    
038    // Attributes
039      
040      /** Holds value of property personId. */
041      private int personId;
042      
043      /** Holds value of property lastName. */
044      private String lastName;
045      
046      /** Holds value of property organisationId. */
047      private int organisationId;
048      
049      /** Tells if this contactPerson already exists in the database */  
050      private boolean addingNew;
051      
052    // Constructors
053      /** Default constructor */
054      public ContactPerson() {
055        super();
056        resetRecord();
057      }
058    
059    // Access methods
060      
061      /** Getter for property personId.
062       * @return Value of property personId.
063       */
064      public int getPersonId() {
065        return this.personId;
066      }
067      
068      /** Setter for property personId.
069       * @param personId New value of property personId.
070       */
071      public void setPersonId(int personId) {
072        this.personId = personId;
073      }
074      
075      /** Getter for property lastName.
076       * @return Value of property lastName.
077       */
078      public String getLastName() {
079        return this.lastName;
080      }
081      
082      /** Setter for property lastName.
083       * @param lastName New value of property lastName.
084       */
085      public void setLastName(String lastName) {
086        this.lastName = lastName;
087        if ((lastName==null) || (lastName.length()==0)) {
088          setOk(false);
089          kotkabeans.Log.log("now adding error form name!!!");
090          addError("Nimi ei voi olla tyhjä!");
091        }
092      }
093    
094      /** Getter for property organisationId.
095       * @return Value of property organisationId.
096       */
097      public int getIntOrganisationId() {
098        return this.organisationId;
099      }  
100      
101      // even if internally int, property must have string getters & setters
102      /** Returns ID of organisation that contact person is related to.
103       * @return The OrganisationId of the contact person.
104       */  
105      public String getOrganisationId() {
106        return Integer.toString(this.organisationId);
107      }
108     
109      /** Setter for property organisationId.
110       * @param organisationId New value of property organisationId.
111       */            
112      public void setOrganisationId(String organisationId) {
113        if (KiuruString.isEmpty(organisationId)) organisationId="0";
114        try {
115          setOrganisationId(Integer.parseInt(organisationId));
116        }
117        catch (Exception e) {
118          setOk(false);
119          addError("Virheellinen kotiorganisaatio!");
120        }
121      }
122      
123      /** Setter for property organisationId.
124       * @param organisationId New value of property organisationId.
125       */         
126      public void setOrganisationId(int organisationId) {
127        if (organisationId<=0) {
128          setOk(false);
129          addError("Henkilöllä on oltava kotiorganisaatio!");
130        }
131        this.organisationId = organisationId;
132      }
133      
134      /** This method sets the internal state of the object into "Post".
135       * @param s Actually not needed. The important thing is that it exists.
136       */  
137      public void setSubmitPost(String s) {
138        setEnumState(EntityHandler.POST_RECORD);
139      }
140    
141    // Operations
142    
143      /**
144       * Implementation of modify rights checking.
145       * This should be called 
146       * @return true is user can modify entity.
147       * @see EntityHandler#hasModifyRight()
148       */
149      protected boolean doCheckModifyRight() {
150        if (getUser().getPersonID()==getPersonId()) return true;
151        return (getUser().getAccessRightLevelID() >= UseModule.ACCESS_RIGHT_LEVEL_TEACHER);
152      }
153    
154      /** Deletes current record from database. NOT IMPLEMENTED YET.
155       * <p>
156       * Actually applies deleted=true. Object is cleared after deletion.
157       */
158      public void deleteRecord() {
159      }
160      
161      /** Retrieves record from database according to current Id field(s)
162       * value(s).
163       * <p>
164       * Id field(s) are defined in descendant classes. Method implements
165       * also user rights check, eg. if user has no right to retrieve
166       * the record, empty object is returned instead.
167       */
168      public void getRecord() {
169        if (getAddingNew()) {
170          throw new IllegalStateException("Cannot get a nonexistent record!");
171        }
172        StringBuffer sb = new StringBuffer(30);
173        sb.append("select * from person where personid=");
174        sb.append(getPersonId());
175        try {
176          RS2 rs = SimpleDb.simpleQuery("Trying to fetch a contactperson record.",
177                                        sb.toString());
178          // if no record is found make a new record.
179          if (!SimpleDb.checkIfEditable(rs)) {
180            resetRecord();
181            return;
182          }
183          setPersonId(rs.getInt("personid"));
184          setLastName(SimpleDb.getString(rs,"lastname"));
185          setOrganisationId(rs.getInt("homeorganisationid"));
186        }
187        catch (Exception e) {
188          resetRecord();
189        }
190      }
191      
192      
193      /** Tells if the data of the contact person has changed.
194       * @return True, if the data of the contact person has changed.
195       * @param db Database connection
196       * @throws Exception If something went wrong in the database handling
197       */  
198      private boolean dataChanged(DB db) throws Exception {
199        if (getAddingNew()) {
200          throw new IllegalStateException("Cannot check whether a new record is changed!");
201        }
202       RS2 rs =  new RS2(db.executeQuery("select * from person where deleted=false and personid ="+getPersonId()));
203        if (rs.next())
204          if ( (rs.getString("lastname").equals(getLastName())) && (rs.getInt("homeorganisationid")==getIntOrganisationId())) {
205            addError("Tietoja ei ole muutettu!");
206            return false;
207          }
208        return true;
209      }
210      
211      /** Saves record to database.
212       * <p>
213       * If field values are not valid, sets Ok property to false.
214       * @throws Exception if there is a problem with DB connection.
215       */
216      public void postRecord() throws Exception {
217        DB db=new DB("ContactPerson.postRecord db");
218        db.connect();
219        PreparedStatement ps=null;
220        try {
221          if (getAddingNew()) { // setting new id from autonumber
222            setPersonId(AutoNumber.getNumber("Person"));
223          }
224          
225          StringBuffer s = new StringBuffer();
226          kotkabeans.Log.log("NOW CHECKING");
227          if ( SimpleDb.recordExists(db, "person", "personId", getPersonId()) ) {
228            if (!dataChanged(db)) {
229              db.disconnect();
230              return; // no changes, we can exit
231            }
232            ps = db.prepareStatement("update person set deleted=false, lastname=?, homeorganistionid=?"+
233            "where personid=?");
234            ps.setString(1, getLastName());
235            ps.setInt(2, getIntOrganisationId());
236            ps.setString(3, Integer.toString(getPersonId()));
237            
238            ps.executeUpdate();
239            addNotice("Yhteyshenkilön "+getLastName()+" tiedot päivitetty!");
240          }
241          else { // insert
242            kotkabeans.Log.log("NOW INSERTING");
243            ps = db.prepareStatement("insert into person "+
244            "(deleted,personid,callname,firstnames,lastname,languageid,homeorganisationid,fundingorganisationid,account,password,registeredon,sessiontimeout,autologout,socsecbirth,socseccentury,socsecend) values "+
245            "('f'    ,?       ,''      ,''        ,?       ,2         ,?                 ,?                    ,''     ,''      ,'now'    ,100,'f',      ''         ,''           ,'')");
246            ps.setInt(1, getPersonId());
247            ps.setString(2, getLastName());
248            ps.setInt(3, getIntOrganisationId());
249            ps.setInt(4, getIntOrganisationId());
250            
251            ps.executeUpdate();
252    //        db.executeUpdate("insert into person (deleted,personid,callname,firstnames,lastname,languageid,homeorganisationid,fundingorganisationid,account,password,registeredon,sessiontimeout,autologout,socsecbirth,socseccentury,socsecend) values ('f'    ,"+getPersonId()+"       ,''      ,''        ,'"+getLastName() +"'      ,2         ,"+getOrganisationId()+"                 ,"+getOrganisationId()+"                    ,''     ,''      ,'now'    ,100,'f',      ''         ,''           ,'')");
253    
254            kotkabeans.Log.log("NOW INSERTED");
255            addNotice("Lisätty yhteyshenkilö "+getLastName()+".");
256          }
257            
258        }
259        finally {
260          if (ps!=null)
261            ps.close();
262          db.disconnect();
263        }  
264      }
265      
266      /** Clears field values.
267       * <p>
268       * Result should be equivalent to constructing a new object.
269       * Nothing is saved to database.
270       *
271       */
272      public void resetRecord() {
273        this.addingNew = true;  // indicates we are adding a new record
274        this.personId = -1;
275        this.lastName = "";
276        this.organisationId = 0;
277      }
278      
279      
280      /** Implementation of parameter clearing. Clears parameters that wasn't given
281       * from the JSP.
282       * @see EntityHandler#clearEmptyParameters(HttpServletRequest)
283       * @param request Request-object from the JSP page.
284       */
285      protected void doClearEmptyParameters(HttpServletRequest request) {
286        if (KiuruString.isEmpty(request.getParameter("lastName"))) {
287          setLastName("");
288        }
289        if (KiuruString.isEmpty(request.getParameter("organisationId"))) {
290          System.out.println("clearing empty organisationid!");
291          setOrganisationId("");
292        }
293      }
294    
295      /** Returns if entity is in a state of adding a new record.
296       * Implementation depends of a descendant class.
297       * @return True if the record doesn't exist in the database, yet.
298       */
299      public boolean getAddingNew() {
300        return this.personId==-1;
301      }
302      
303      
304      /** Implementation of clearing action state.
305       * @see EntityHandler#clearEmptyParameters(HttpServletRequest)
306       * @param request The request-object from the JSP-page.
307       */
308      protected void doClearActionState(HttpServletRequest request) {
309        /* http parameter test must be applied, othervise page may not be cleared
310           when called multiple times. personid=-1 -comparison is not advisable
311           because the page would be cleared then. */
312        if (KiuruString.isEmpty(request.getParameter("personId"))) 
313          setEnumState(EntityHandler.RESET_RECORD);
314        else
315          setEnumState(EntityHandler.NO_ACTION);
316      }  
317      
318    }  
319    /***************************************************************************************************
320     *               COPYRIGHT (C) KIURU -PROJECT GROUP
321     *               Limited rights granted. Please refer to license.
322     **************************************************************************************************/