1package example
2
3uses java.util.*
4
5uses java.io.File
6
7class Person extends Contact implements IEmailable {
8
9  var _name : String
10  var _age : Integer as Age
11  var _relationship : Relationship as readonly RelationshipOfPerson
12
13  delegate _emailHelper represents IEmailable
14
15  enum Relationship {
16    FRIEND,
17    FAMILY,
18    BUSINESS_CONTACT
19  }
20
21  // Map of names to people
22  static var ALL_PEOPLE = new HashMap<String, Person>()
23
24  /* Constructs a new Person */
25  construct( name : String, age : Integer, relationship : Relationship ) {
26    _name = name
27    _age = age
28    _relationship = relationship
29    _emailHelper = new EmailHelper( this )
30  }
31
32  property get Name():String{
33    return _name
34  }
35
36  property set Name(name : String){
37    _name = name
38  }
39
40  /* Implement IEmailable#getEmailName() */
41  override function getEmailName():String{
42    return Name
43  }
44
45  function incrementAge() {
46    _age++
47  }
48
49  @Deprecated
50  function printPersonInfo() {
51    print( "Person { Name : ${Name}, Age : ${Age}, Relationship : ${RelationshipOfPerson} }" )
52  }
53
54  static function addPerson(p : Person){
55    if(ALL_PEOPLE.containsKey(p?.Name)) {
56      throw new IllegalArgumentException( "There is already someone named '${p.Name}'." )
57    }
58    ALL_PEOPLE[p.Name] = p
59  }
60
61  static function addAllPeople( contacts : List<Contact> ) {
62    for( contact in contacts ) {
63      if( contact typeis Person and not ALL_PEOPLE.containsKey( contact.Name )) {
64        addPerson( contact )
65      }
66    }
67  }
68
69  static function getAllPeopleOlderThanNOrderedByName( age : int ) {
70    var allPeople = ALL_PEOPLE.Values
71
72    return allPeople.where( \ p -> p.Age > age ).orderBy( \ p -> p.Name )
73  }
74
75  static function loadPersonFromDB( id : Integer ) {
76    using( var conn = DBConnectionManager.getConnection(),
77      var stmt = conn.prepareStatement( "SELECT name, age, relationship FROM PEOPLE WHERE ID=?") ){
78
79      stmt.setInt( 0, 0 )
80      var result = stmt.executeQuery()
81      if( result.next() ) {
82         addPerson( new Person( result.getString( "name" ),
83                    result.getInt( "age" ),
84                    Relationship.valueOf( result.getString( "relationship" ) ) ) )
85
86      }
87    }
88  }
89
90  /* Loads in people from a CSV */
91  static function loadFromFile( file : File ) {
92    file.eachLine( \ line -> {
93      if( line.HasContent ) {
94        addPerson( line.toPerson() )
95      }
96    })
97  }
98
99  /* Save people to a CSV */
100  static function saveToFile( file : File ) {
101    using( var writer = new FileWriter( file ) ) {
102      print( PersonCSVTemplate.renderToString( ALL_PEOPLE.Values ) )
103      PersonCSVTemplate.render( writer, ALL_PEOPLE.Values )
104    }
105  }
106}