001    /***************************************************************************************************
002     *               MODULE DESCRIPTION
003     ****************************************************************************************************
004     *
005     *               NAME:           SpaceGroup.java
006     *               LANGUAGE:       Java2
007     *               DATE:           2.12.2002
008     *               AUTHOR:         Miika Nurminen, Jyväskylän yliopisto
009     *
010     ****************************************************************************************************
011     *               COPYRIGHT (C) Kiuru-Group
012     *               Limited rights granted. Please refer to license
013     ****************************************************************************************************
014     *  
015     ****************************************************************************************************
016     *               UPDATES
017     ****************************************************************************************************
018     *
019     * 2.12.2002
020     *  initial release
021     * 30.1.2003 / mn
022     *  fixed bug in addtofavorites
023     * 15.5.2003 / mn
024     *  implemented as enum class
025     *   
026     ****************************************************************************************************/
027    package kiurubeans;
028    
029    import java.beans.*;
030    import kiurubeans.*;
031    import kotkabeans.*;
032    import java.sql.*;
033    import javax.servlet.http.HttpServletRequest;
034    
035    /**
036     * Encapsulation of SpaceGroup data entity.
037     */
038    public class SpaceGroup extends EntityHandler {
039    
040    // Attributes
041    
042      // SpaceGroup modifyRights
043      /**  no modify right */
044      public static final int ACCESSLEVEL_NONE=0; 
045      /** right to modify contents of the spacegroup, but no reserver's access levels*/
046      public static final int ACCESSLEVEL_NORMAL=1; 
047      /** all modify rights */
048      public static final int ACCESSLEVEL_FULL=2; 
049    
050      /** Selects spaces for this spacegroup */
051      public static final int ADD_SPACES=5;
052      /** Selects reservers for this spacegroup */
053      public static final int ADD_PERSONS=6;
054      /** Confirms adding spaces for this spacegroup */
055      public static final int ADD_SPACE_CONFIRM=7;
056      /** Confirms adding reservers for this spacegroup */
057      public static final int ADD_PERSON_CONFIRM=8;
058      /** Removes spaces from this spacegroup*/
059      public static final int DELETE_SPACES=9;
060      /** Removes reservers from this spacegroup*/
061      public static final int DELETE_PERSONS=10;
062    
063      /** Name of this spacegroup */
064      private String name = "";
065      /** Spacegroup description */
066      private String description ="";
067      /** Spacegroup's id. -1 indicates a new space. */
068      private int spaceGroupId = -1;
069    
070      /**
071       * Spacegroup's type. Spacegroup types are defined as follows:
072       * <p>
073       *  1 - Rakennus<br>
074       *  2 - Alue<br>
075       *  3 - Oheisvarattavan toimituspaikat<br>
076       *  4 - Hallinnollinen saliryhmä<br>
077       *  5 - Henkilökohtainen saliryhmä<br>
078       *  6 - Henkilökohtainen mielisaliryhmä
079       * <p>
080       * These should be put in a separate enum structure.
081       */
082      private int spaceGroupType = 5;  // 5 == henkilökohtainen saliryhmä
083      
084      /**
085       * User's selected spaces to be joined in this spacegroup.
086       */
087      private String[] selectedSpaces = new String[0];
088      /**
089       * User's selected reservers to be joined in this spacegroup.
090       */
091      private String[] selectedPersons = new String[0];
092      
093      /** determines if user has right to modify contents of this group
094          (0=none, 1=limited, 2=full, including reservation levels ) */
095      private int modifyRight = ACCESSLEVEL_NONE; 
096      
097      /** minimum accessrightlevel for reservation requests */
098      private int accessRightLevelId = 2; 
099    
100    // Constructors
101      
102      /** Dummy empty constructor */
103      public SpaceGroup() {
104      }
105    
106    // Access methods
107      
108      /** Returns current max state value. Inherited classes may override this
109       *  to introduce new states.
110       * @return Current max state value.
111       */
112      protected int getMaxState() {  return 10;  }
113    
114      /** Returns the name of the spaceGroup
115       * @return Name of the spaceGroup
116       */  
117      public String getName() { return this.name; }
118    
119      /** Sets the name of the spaceGroup.
120       * @param name Name of the spacegroup
121       */  
122      public void setName(String name) { 
123        String s = KiuruString.sqlTrim(name);
124        if (s.length()==0) {
125          setOk(false);
126          addError("Nimi ei voi olla tyhjä!");
127          return;
128        }
129        this.name = s; 
130      }
131      
132      /**
133       * Returns current spacegroup's type as string.
134       * @return current spacegroup's type as string
135       */  
136      public String getTypeAsString() {
137        String result="";
138        try {
139          RS2 rs = SimpleDb.simpleQuery("SpaceGroup.getTypeAsString", "select name from spacegrouptype where deleted=false and spacegrouptypeid="+getType());
140          if (rs.next()) {
141            result=rs.getString("name");
142          }
143        } 
144        catch (Exception e) {
145        }
146        return result;
147      }
148      
149      /**
150       * Returns current spacegroup's type id.
151       * @return current spacegroup's type id.
152       */  
153      public int getType() {return spaceGroupType;}
154    
155      /**
156       * Setter for attribute spaceGroupType.
157       * @param spaceGroupType new spacegroup type id.
158       */  
159      public void setType(int spaceGroupType) {this.spaceGroupType=spaceGroupType;}
160      
161      /**
162       * Getter for attribute spaceGroupId.
163       * @return spacegroup id.
164       */  
165      public int getSpaceGroupId() {return spaceGroupId;}
166    
167      /**
168       * Setter for attribute spaceGroupId. Use with caution, 
169       * this should be persistent for an object. -1 indicates a new record.
170       * @param spaceGroupId new spacegroup id.
171       */  
172      public void setSpaceGroupId(int spaceGroupId) {this.spaceGroupId=spaceGroupId;}
173      
174      /**
175       * Getter for attribute description.
176       * @return spacegroup description
177       */  
178      public String getDescription() { return this.description; }
179      
180      /**
181       * Setter for attribute description.
182       * @param desc new spacegroup description
183       */  
184      public void setDescription(String desc) { this.description = kotkabeans.Encoder.SQLEncode(desc); }
185    
186      /**
187       * Getter for attribute selectedSpaces.
188       * @return The spaces the user has selected for this spacegroup.
189       */  
190      public String[] getSelectedSpaces() { return selectedSpaces; }
191      
192      /**
193       * Setter for attribute selectedSpaces.
194       * @param s The spaces the user has selected for this spacegroup.
195       */  
196      public void setSelectedSpaces(String[] s) { selectedSpaces=s; }
197    
198      /**
199       * Sets the <i>i</i>th selected space
200       *
201       * @param i Which space is going to be set
202       * @param s The id of the selected space
203       */  
204      public void setSelectedSpaces(int i,String s) { selectedSpaces[i]=s; }
205    
206      /** Returns the <i>i</i>th selected space
207       * @return The id of the selected space
208       * @param i Which space is given
209       */  
210      public String getSelectedSpaces(int i) { return selectedSpaces[i]; }
211      
212      /**
213       * Getter for attribute selectedPersons.
214       * @return The reservers the user has selected for this spacegroup.
215       */  
216      public String[] getSelectedPersons() { return selectedPersons; }
217    
218      /**
219       * Setter for attribute selectedPersons.
220       * @param s The reservers the user has selected for this spacegroup.
221       */  
222      public void setSelectedPersons(String[] s) { selectedPersons=s; }
223    
224      /**
225       * Sets the <i>i</i>th selected person
226       *
227       * @param i Which person is going to be set
228       * @param s The id of the selected person
229       */  
230      public void setSelectedPersons(int i,String s) { selectedPersons[i]=s; }
231    
232      /** Returns the <i>i</i>th selected person
233       * @return The id of the selected person
234       * @param i Which person is given
235       */  
236      public String getSelectedPersons(int i) { return selectedPersons[i]; }
237    
238    
239      /**
240       * Returns required accessrightlevel for this spacegroup as string in user's
241       * own language. Accessrightlevel determines right to make reservation requests.
242       * @return accessrightlevel
243       */  
244      public String getAccessRightLevelAsString() {
245        String result="";
246        try {
247          RS2 rs = SimpleDb.simpleQuery("SpaceGroup.getAccessRightLevelAsString", "select name from accessrightleveltranslation where accessrightlevelid="+getAccessRightLevelId()+" and languageid="+getUser().getLanguageID());
248          if (rs.next()) {
249            result=rs.getString("name");
250          }
251        } 
252        catch (Exception e) {
253        }
254        return result;
255      }
256      
257      
258      /**
259       * Getter for attribute accessRightLevelId.
260       * @return required accessrightlevel for this spacegroup
261       */  
262      public int getAccessRightLevelId() { return this.accessRightLevelId; }
263      
264      /** Sets minimum accessRightLevel for reservation requests in this spacegroup
265       * Assumes accessrightlevelid is between 1..6
266       * @param i Minimum accessRightLevel
267       */            
268      public void setAccessRightLevelId(int i) {
269        this.accessRightLevelId=i;
270      }
271      
272     
273      /** Used with html forms. Changes bean state to AddNew.
274       * 'this' should be initialized!
275       * @param s We are not interested in the content of the string, because
276       * it can vary.
277       */
278      public void setSubmitAdd(String s) {
279        setEnumState(EntityHandler.RESET_RECORD);
280      }
281      
282      /** Used with html forms. Changes bean state to searchWithId, so 'this' can
283       * be modified.
284       * id property should be set before call to performAction
285       * @param s We are not interested in
286       */
287      public void setSubmitModify(String s) {
288        setEnumState(EntityHandler.GET_RECORD);
289      }
290    
291      /** Used with html forms. Changes the internal state of the bean.
292       * @param s We are not interested in the content of the string, because it can vary.
293       */
294      public void setSubmitPost(String s) {
295        setEnumState(EntityHandler.POST_RECORD);
296      }
297      
298      /** Used with html forms. Changes the internal state of the bean.
299       * @param s We are not interested in the content of the string, because it can vary.
300       */
301      public void setSubmitDelete(String s) {
302        setEnumState(EntityHandler.DELETE_RECORD);
303      }
304      
305      /** Used with html forms. Changes the internal state of the bean.
306       * @param s We are not interested in the content of the string, because it can vary.
307       */
308      public void setSubmitAddSpace(String s) {
309        setEnumState(ADD_SPACES);
310      }
311    
312      /** Used with html forms. Changes the internal state of the bean.
313       * @param s We are not interested in the content of the string, because it can vary.
314       */
315      public void setSubmitAddSpaceConfirm(String s) {
316        setEnumState(ADD_SPACE_CONFIRM);
317      }
318      
319      /** Used with html forms. Changes the internal state of the bean.
320       * @param s We are not interested in the content of the string, because it can vary.
321       */
322      public void setSubmitDeleteSpace(String s) {
323        setEnumState(DELETE_SPACES);
324      }
325      
326      /** Used with html forms. Changes the internal state of the bean.
327       * @param s We are not interested in the content of the string, because it can vary.
328       */
329      public void setSubmitAddPersons(String s) {
330        setEnumState(ADD_PERSONS);
331      }
332    
333      /** Used with html forms. Changes the internal state of the bean.
334       * @param s We are not interested in the content of the string, because it can vary.
335       */
336      public void setSubmitAddPersonConfirm(String s) {
337        setEnumState(ADD_PERSON_CONFIRM);
338      }
339      
340      /** Used with html forms. Changes the internal state of the bean.
341       * @param s We are not interested in the content of the string, because it can vary.
342       */
343      public void setSubmitDeletePersons(String s) {
344        setEnumState(DELETE_PERSONS);
345      }
346    
347      /**
348       * Getter for attribute modifyRight.
349       * @return current user's modify right state
350       */  
351      public int getModifyRight() {
352        return modifyRight;
353      }
354      
355    
356    // Operations
357        
358      /** Performs action based on actionType (eg. addNew, modify, post, delete).
359       * Inherited classes may override this method to introduce custom actions.
360       * @throws Exception If something went wrong during database operations.
361       */
362      protected void defaultAction() throws java.lang.Exception {
363        switch (getEnumState()) {
364          case ADD_SPACE_CONFIRM:
365            addSpaces();
366          break;
367          case ADD_PERSON_CONFIRM: 
368            addPersons();
369          break;
370          case DELETE_SPACES:
371            postRecord(); //super.defaultAction(); // post
372            deleteSpaces();
373          break;
374          case DELETE_PERSONS:
375            postRecord(); //super.defaultAction(); // post
376            deletePersons();
377          break;
378          default:
379            super.defaultAction(); // post
380          break;
381        }
382      }
383    
384      /** Returns all spacegrouptypes from database.
385       * @return <CODE>RS2</CODE> containing <CODE>name</CODE> and <CODE>spacegroutypeid</CODE>
386       * of all possible spacegrouptypes.
387       * @throws Exception If something went wrong during database operations.
388       */
389      public static RS2 getSpaceGroupTypes() throws Exception {
390        // note! the result should be customized according to user's access rights
391        return SimpleDb.simpleQuery("Getting SpaceGroupTypes","select name,spacegrouptypeid from spacegrouptype where deleted=false");
392      }
393      
394      
395      /** Assigns SpaceGroup's properties according to current SpaceGroupId
396       * @throws Exception If something went wrong during database operations.
397       */
398      public void assignSpaceGroupFromDataBase() throws Exception {
399        DB db=new DB("Space-beania");
400        db.connect();
401        try {
402          assignSpaceGroupFromDataBase(db);
403        }
404        finally {
405          db.disconnect();
406        }
407      }
408      
409      /**
410       * Assigns SpaceGroup's properties according to current SpaceGroupId
411       * using existing db connection.
412       * @param db open db connection.
413       * @throws Exception If something went wrong during database operations.
414       */  
415      public void assignSpaceGroupFromDataBase(DB db) throws Exception {
416        RS2 rs;
417          rs = new RS2(db.executeQuery("select deleted,name as spacegroupname,spacegroupid,spacegrouptypeid,description,accessrightlevelid from spacegroup "+
418          "where spacegroupid="+KiuruString.sqlQuote(getSpaceGroupId())));
419          if (!SimpleDb.checkIfEditable(rs)) 
420            return;
421          setName(SimpleDb.getString(rs,"spacegroupname"));
422          setType(rs.getInt("spacegrouptypeid"));
423          setDescription(SimpleDb.getString(rs,"description"));
424          setAccessRightLevelId(rs.getInt("accessrightlevelid"));
425        
426          setSelectedSpaces(null);
427          setSelectedPersons(null);
428      }
429      
430    
431      /**
432       * Checks if object field value are same as in database.
433       * @param db open db connection
434       * @throws Exception If something went wrong during database operations.
435       */
436      private boolean dataChanged(DB db) throws Exception {
437        RS2 rs =  new RS2(db.executeQuery("select name,spacegrouptypeid,description,accessrightlevelid from spacegroup where deleted=false and spacegroupid ="+getSpaceGroupId()));
438        if (rs.next())
439          if ( (rs.getString("name").equals(getName())) && (rs.getInt("spacegrouptypeid")==getType()) && (rs.getInt("accessrightlevelid")==getAccessRightLevelId()) && (rs.getString("description").equals(getDescription())) ) {
440            if (getEnumState()==EntityHandler.POST_RECORD/*getActionType().equals("postData")*/) addNotice("Tietoja ei ole muutettu!");
441            // no notices if adding spaces to spacegroup etc. 25.4.2003 / mn
442            return false;
443          }
444        return true;
445      }
446      
447      /**
448       * Saves current spacegroup object to database
449       * @throws Exception If something went wrong during database operations.
450       */  
451      public void putSpaceGroupToDataBase() throws Exception {
452        DB db=new DB("SpaceGroup.putSpaceGroupToDataBase db");
453        db.connect();
454        try {
455          putSpaceGroupToDataBase(db);
456        }
457        finally {
458          db.disconnect();
459        }
460        
461      }
462    
463      /**
464       * Saves current spacegroup object to database
465       * @param db open db connection
466       * @throws Exception If something went wrong during database operations.
467       */  
468      public void putSpaceGroupToDataBase(DB db) throws Exception {
469        PreparedStatement ps=null;
470          if (getSpaceGroupId()==-1) { // setting new id from autonumber
471            setSpaceGroupId(AutoNumber.getNumber("SpaceGroup"));
472          }
473        try {  
474          StringBuffer s = new StringBuffer();
475          if ( SimpleDb.recordExists(db, "SpaceGroup", "SpaceGroupId", getSpaceGroupId()) ) {
476            if (!dataChanged(db)) {
477              db.disconnect();
478              return; // no changes, we can exit
479            }
480            ps = db.prepareStatement("update spacegroup set deleted=false, name=?, spacegrouptypeid=?, description=?, accessrightlevelid=? "+
481            "where spacegroupid=?");
482            ps.setString(1, getName());
483            ps.setInt(2, getType());
484            ps.setString(3, getDescription());
485            ps.setInt(4, getAccessRightLevelId());
486            ps.setInt(5, getSpaceGroupId());
487            
488            addNotice("Saliryhmän "+getName()+" tiedot päivitetty!");
489            ps.executeUpdate();
490          }
491          else { // insert
492         //  this block _should_  work... if it doesnt, try the db.executeUpdate statement below...
493            ps = db.prepareStatement("insert into spacegroup (name,spacegrouptypeid,description,spacegroupid,deleted,accessrightlevelid) values (?,?,?,?,?,?)");
494            ps.setString(1, getName());
495            ps.setInt(2, getType());
496            ps.setString(3, getDescription());
497            ps.setInt(4, getSpaceGroupId());
498            ps.setBoolean(5,false);
499            ps.setInt(6, getAccessRightLevelId());
500            
501            ps.executeUpdate();
502    /*        db.executeUpdate("insert into spacegroup (name,spacegrouptypeid,description,spacegroupid,"+
503            "deleted,accessrightlevelid) values ("+
504            "'"+getName()+"',"+getType()+",'"+getDescription()+"',"+getSpaceGroupId()+
505            ",false,"+getAccessRightLevelId()+");");*/
506            addNotice("Lisätty saliryhmä "+getName()+".");
507            // adding user to spacegroup as modifier:
508            userToNewSpaceGroup(db);
509          }
510        }
511        finally {
512          if (ps!=null)
513            ps.close();
514        }
515      }
516      
517      /**
518       *  Deletes current spacegroup + relations to spaces & persons
519       */
520      public void deleteRecord() {
521        StatementContainer[] sc = new StatementContainer[3];
522        sc[0]=new StatementContainer("update spacegroup set deleted=true where spacegroupid = ?");
523        sc[0].addStatement(new IntItem(getSpaceGroupId()));
524    
525        sc[1]=new StatementContainer("update spacegroupspace set deleted=true where spacegroupid = ?");
526        sc[1].addStatement(new IntItem(getSpaceGroupId()));
527        
528        sc[2]=new StatementContainer("update spacegroupperson set deleted=true where spacegroupid = ?");
529        sc[2].addStatement(new IntItem(getSpaceGroupId()));
530        
531        if (SimpleDb.executeTransaction(sc, "SpaceGroup.deleteRecord db")) {
532          addNotice("Saliryhmä "+getName()+" poistettu!");
533        }
534        else {
535          addError("Virhe saliryhmää "+getName()+" poistettaessa. Mitään ei poistettu.");    
536        }
537      }
538      
539      /**
540       * Deletes selected spaces from current spacegroup
541       */
542      public void deleteSpaces() {
543        if ((getSelectedSpaces()==null) || (getSelectedSpaces().length==0)) {
544          addError("Poistettavia saleja ei valittu!");    
545          return;
546        }
547        // this should be replaced with a single container with varying parameters!
548        StatementContainer[] sc = new StatementContainer[getSelectedSpaces().length];
549        for (int i=0; i<getSelectedSpaces().length; i++) {
550          sc[i]=new StatementContainer("update spacegroupspace set deleted=true where spacegroupid = ? and spaceid = ?");
551          sc[i].addStatement(new IntItem(getSpaceGroupId()));
552          sc[i].addStatement(new IntItem((Integer.parseInt(getSelectedSpaces(i)))));
553        }
554        if (SimpleDb.executeTransaction(sc, "SpaceGroup.deleteSpaces db")) {
555          addNotice("Salit poistettu saliryhmästä!");
556        }
557        else {
558          addError("Virhe saleja poistettaessa. Mitään ei poistettu.");    
559        }
560      }
561    
562      /**
563       * Deletes selected persons from current spacegroup
564       */
565      public void deletePersons() {
566        if ((getSelectedPersons()==null) || (getSelectedPersons().length==0)) {
567          addError("Poistettavia henkilöitä ei valittu!");    
568          return;
569        }
570        StatementContainer[] sc = new StatementContainer[getSelectedPersons().length];
571        for (int i=0; i<getSelectedPersons().length; i++) {
572          sc[i]=new StatementContainer("update spacegroupperson set deleted=true where spacegroupid = ? and personid = ?");
573          sc[i].addStatement(new IntItem(getSpaceGroupId()));
574          sc[i].addStatement(new IntItem((Integer.parseInt(getSelectedPersons(i)))));
575        }
576        if (SimpleDb.executeTransaction(sc, "SpaceGroup.deletePersons db")) {
577          addNotice("Henkilöt poistettu saliryhmästä!");
578        }
579        else {
580          addError("Virhe henkilöitä poistettaessa. Mitään ei poistettu.");    
581        }
582      }
583      
584      /** Adds selected spaces to current spacegroup
585       * @throws Exception If something went wrong during database operations.
586       */
587      public void addSpaces() throws java.lang.Exception {
588        DB db = new DB("addSpaces()");
589        db.connect();
590        try {
591          addSpaces(db);
592        }
593        finally {
594          db.disconnect();
595        } 
596      }
597    
598      /** Adds selectedSpaces to the current spaceGroup.
599       * @param db Database connection
600       * @throws Exception If something went wrong during database operations.
601       */
602      public void addSpaces(DB db) throws java.lang.Exception {
603        if (getSelectedSpaces().length==0) {
604          addError("lisättäviä saleja ei valittu!");    
605          return;
606        }
607        // this should be replaced with a single container with varying parameters!
608        StatementContainer[] sc = new StatementContainer[getSelectedSpaces().length];
609        
610        String insertStr = "insert into spacegroupspace (deleted,spacegroupid,spaceid) values (false,"+getSpaceGroupId()+",?)";
611        String updateStr = "update spacegroupspace set deleted=false where spacegroupid="+getSpaceGroupId()+" and spaceid=?";
612          
613        // checking  if spacegroups exist
614        StringPair[] sp = new StringPair[2];
615        sp[0] = new StringPair("spacegroupid", Integer.toString(getSpaceGroupId()));
616        sp[1] = new StringPair("spaceid");
617        for (int i=0; i<getSelectedSpaces().length; i++) {
618          sp[1].setValue(getSelectedSpaces(i));
619          if (SimpleDb.recordExists(db,"SpaceGroupSpace",sp))
620            sc[i]=new StatementContainer(updateStr);
621          else
622            sc[i]=new StatementContainer(insertStr);
623          
624          sc[i].addStatement(new IntItem((Integer.parseInt(getSelectedSpaces(i)))));
625        }
626    
627          
628        if (SimpleDb.executeTransaction(sc, "SpaceGroup.addSpaces db",db)) {
629          addNotice("Salit lisätty saliryhmään!");
630        }
631        else {
632          addError("Virhe saleja lisättäessä. Mitään ei lisätty.");    
633        }
634        if (getSelectedSpaces().length==0) {
635          addError("Lisättäviä saleja ei valittu!");    
636          return;
637        }
638      }
639      
640      /** Adds selectedPersons to the current spaceGroup. This method opens new DB.
641       * @throws Exception If something went wrong during database operations.
642       */
643      public void addPersons() throws java.lang.Exception {
644        DB db = new DB("addPersons()");
645        try {
646          addPersons(db);
647        }
648        finally {
649          db.disconnect();
650        }
651      }
652      
653      /** Adds selected persons into the current spaceGroup
654       * @param db Database connection
655       * @throws Exception If something went wrong during database operations.
656       */
657      public void addPersons(DB db) throws java.lang.Exception {
658        if (getSelectedPersons().length==0) {
659          addError("Lisättäviä henkilöitä ei valittu!");
660          return;
661        }
662        // this should be replaced with a single container with varying parameters!
663        StatementContainer[] sc = new StatementContainer[getSelectedPersons().length];
664        
665        String insertStr = "insert into spacegroupperson (deleted,spacegroupid,personid) values (false,"+getSpaceGroupId()+",?)";
666        String updateStr = "update spacegroupperson set deleted=false where spacegroupid="+getSpaceGroupId()+" and personid=?";
667          
668          // checking  if spacegroups exist
669          StringPair[] sp = new StringPair[2];
670          sp[0] = new StringPair("spacegroupid", Integer.toString(getSpaceGroupId()));
671          sp[1] = new StringPair("personid");
672          for (int i=0; i<getSelectedPersons().length; i++) {
673            sp[1].setValue(getSelectedPersons(i));
674            if (SimpleDb.recordExists(db,"SpaceGroupPerson",sp))
675              sc[i]=new StatementContainer(updateStr);
676            else
677              sc[i]=new StatementContainer(insertStr);
678            sc[i].addStatement(new IntItem((Integer.parseInt(getSelectedPersons(i)))));
679          }
680        
681        if (SimpleDb.executeTransaction(sc, "SpaceGroup.addPersons db",db)) {
682          addNotice("Henkilöt lisätty saliryhmän käyttäjiksi!");
683        }
684        else {
685          addError("Virhe henkilöitä lisättäessä. Mitään ei lisätty.");
686        }
687        if (getSelectedPersons().length==0) {
688          addError("Lisättäviä henkilöitä ei valittu!");
689          return;
690        }
691      }
692      
693      /**
694       * Adds current user to _new_ (should be current) spacegroup.
695       * @param db open db connection
696       * @throws Exception If something went wrong during database operations.
697       */
698      private void userToNewSpaceGroup(DB db) throws java.lang.Exception {
699          String s = null;
700          if (SimpleDb.recordExists(db,"SpaceGroupPerson",
701              new StringPair[] {
702               new StringPair("spacegroupid", Integer.toString(getSpaceGroupId())),
703               new StringPair("personid",Integer.toString(getUser().getPersonID()))
704              })) {
705            s = ("update spacegroupperson set deleted=false, accesslevel=0, modifyright=1 where spacegroupid="+getSpaceGroupId()+" and personid="+getUser().getPersonID());
706          }
707          else {
708            s = ("insert into spacegroupperson (deleted,modifyright,accesslevel,spacegroupid,personid) values (false,1,0,"+getSpaceGroupId()+","+getUser().getPersonID()+")");
709          }
710          db.executeUpdate(s);
711      }
712      
713      /** Adds given spaces to user's favorites
714       * @param error <CODE>error</CODE> where error messages are sent to
715       * @param user User whose favorite list spaces are added
716       * @param spaces array of spaces' id numbers as strings
717       * @throws Exception If something went wrong during database operations.
718       */
719      public static void addToFavorites(kotkabeans.Error error,User user, String[] spaces) throws java.lang.Exception {
720        // first we check if favorites exist
721        RS2 rs = SpaceGroupSearch.getFavoriteSpaceGroup(user.getPersonID());
722        SpaceGroup  g = new SpaceGroup();
723        g.setError(error);
724        g.setUser(user);
725        DB db = new DB("addToFavorites");
726        db.connect();
727        try {
728          if (rs!=null && rs.next()) {
729            g.setSpaceGroupId(rs.getInt("spacegroupid"));
730    
731            g.assignSpaceGroupFromDataBase(db);
732          }
733          else {
734            g.setName("Mielisalit_"+user.getAccount());
735            g.setType(6); // 6==henkilökohtainen mielisaliryhmä
736            g.putSpaceGroupToDataBase(db);
737          }
738          g.setSelectedSpaces(spaces);
739          g.addSpaces(db);
740        
741          db.executeUpdate("Update spacegroupperson set modifyright=1 "+
742            "where spacegroupid="+g.getSpaceGroupId()+" and personid="+user.getPersonID() );
743        }
744        finally {
745          db.disconnect();
746        }
747      }
748      
749      /**
750       * Returns true is user has right to modify contents of current spacegroup.
751       * (Administrators & persons with modifyRight)
752       * Note! User must be set for this method!
753       */
754      public void updateModifyRight() {
755        if ((getUser()!=null) && (getUser().hasAdminRight())) {
756          this.modifyRight=2;
757          return;
758        }
759        else 
760        if (getEnumState()==RESET_RECORD/*getActionType().equals("addNew")*/) {
761          this.modifyRight=1;
762          return;
763        }
764        else this.modifyRight=0;
765      
766        try {
767          RS2 rs = SimpleDb.simpleQuery("SpaceGroup.hasModifyRight db", 
768           "select modifyright,accesslevel from spacegroupperson "+
769           "where deleted=false "+
770           "and personid="+getUser().getPersonID()+" and spacegroupid="+getSpaceGroupId() );
771            
772          if (rs.next()) {
773            if (rs.getInt("modifyright")!=0) {
774              if (rs.getInt("accesslevel")==2) 
775                this.modifyRight=2;
776              else
777                this.modifyRight=1;
778            }
779          }
780        }
781        catch (Exception e) {
782        }
783      }
784     
785      /** Checks modify right for spaceGroup with given id. if spaceGroup does not exist
786       *  or other error is encountered returns 0.
787       * @param db Database connection
788       * @param user User who wants to modify spaceGroup
789       * @param spaceGroupId SpaceGroupId of the to be modified spaceGroup
790       * @throws Exception If something went wrong during database operations.
791       * @return <CODE>true</CODE> if user is allowed to modify spaceGroup
792       */
793      public static int checkModifyRight(DB db,User user,int spaceGroupId) throws java.lang.Exception {
794        if (user.hasAdminRight()) {
795          return 2;
796        }
797        
798        RS2 rs = new RS2(db.executeQuery(
799        "select modifyright,accesslevel from spacegroupperson where deleted=false "+
800        "and personid="+user.getPersonID()+" and spacegroupid="+spaceGroupId
801        ));
802        
803        if (rs.next()) {
804          if (rs.getInt("modifyright")!=0) {
805            if (rs.getInt("accesslevel")==2)
806              return 2;
807            else
808              return 1;
809          }
810        }
811        return 0;
812      }
813      
814     
815      /** Implementation of modify rights checking. Notify that SpaceGroup
816       * has also additional modifyrights scheme. This method returns true
817       * only if user has full modifyright.
818       * @return true is user can modify entity.
819       * @see EntityHandler#hasModifyRight()
820       */
821      protected boolean doCheckModifyRight() {
822        updateModifyRight();
823        return (this.modifyRight==2);
824      }
825      
826     
827      /** Implementation of parameter clearing.
828       * @see EntityHandler#clearEmptyParameters(HttpServletRequest)
829       * @param request <CODE>request</CODE>-object from the JSP page.
830       */
831      protected void doClearEmptyParameters(HttpServletRequest request) {
832        if (KiuruString.isEmpty(request.getParameter("name"))) setName("");
833      }
834      
835      /** Returns <CODE>true</CODE> if entity is in a state of adding a new record.
836       * Implementation depends of a descendand class.
837       * @return <CODE>True</CODE> if entity is in a state of adding a new record.
838       */
839      public boolean getAddingNew() {
840        return (getSpaceGroupId()==-1);
841      }
842      
843      /** Retrieves record from database according to current Id field(s)
844       * value(s).
845       * <p>
846       * Id field(s) are defined in descendant classes. Method implements
847       * also user rights check, eg. if user has no right to retrieve
848       * the record, empty object is returned instead.
849       *
850       * @throws Exception if there is a problem with DB connection
851       */
852      public void getRecord() throws Exception {
853        assignSpaceGroupFromDataBase();
854      }
855      
856      /** Saves record to database.
857       * <p>
858       * If field values are not valid, sets Ok property to false.
859       *
860       * @throws Exception if there is a problem with DB connection
861       */
862      public void postRecord() throws Exception {
863         putSpaceGroupToDataBase(); 
864      }
865      
866      /** Clears field values.
867       * <p>
868       * Result should be equivalent to constructing a new object.
869       * Nothing is saved to database.
870       */
871      public void resetRecord() {
872        setSpaceGroupId(-1);
873        setType(5);
874        setAccessRightLevelId(2);
875        this.name="";
876        setDescription("");
877        setSelectedSpaces(null);
878        setSelectedPersons(null);
879      }
880      
881      /** Default implementation of clearing action state. Descendant classes may
882       * override this.
883       * @see EntityHandler#resetActionState(HttpServletRequest)
884       * @param request The request-object of the JSP.
885       */
886      protected void doClearActionState(javax.servlet.http.HttpServletRequest request) {
887        if ((getEnumState()==KiuruHandler.NO_ACTION) && (!KiuruString.isEmpty(request.getParameter("spaceGroupId")))) 
888          setEnumState(GET_RECORD); // if modifyrecord is not in URL, this simulates it.
889        else super.doClearActionState(request);
890      }
891    
892    }
893    /***************************************************************************************************
894     *               COPYRIGHT (C) KIURU -PROJECT GROUP
895     *               Limited rights granted. Please refer to license.
896     **************************************************************************************************/