Wiki source code of Your First Rest Project

Version 11.1 by Pascal Robert on 2011/12/27 22:21

Show last authors
1 {{toc}}{{/toc}}
2
3 = Introduction =
4
5 In the first part of the Blog tutorial, you will learn:
6
7 * How to create a EOModel for the database (we will use H2)
8 * How to use migrations to create the database tables
9 * How to use ERRest to create blog posts with JSON format and how to display the blog posts in HTML for readers
10
11 = Create a new project =
12
13 You will need to create a new project for this tutorial. In Eclipse, open the **File** menu, select **New** and select **Wonder REST Application**. Name your project as //BlogRest//.
14
15 = Create the database model =
16
17 == Database structure ==
18
19 We will build a small database model for the blog. The database will have two tables: BlogEntry and Author.
20
21 BlogEntry will have the following columns:
22
23 |= Column name |= Type |= Constraints
24 | id | integer | primary key
25 | title | string(255) |
26 | content | string(4000) |
27 | creationDate | timestamp |
28 | author | integer | relation with Author
29
30 Author will have the following columns:
31
32 |= Column name |= Type |= Constraints
33 | id | integer | primary key
34 | firstName | string(50) |
35 | lastName | string(50) |
36 | email | string(100) | unique
37
38 == Creating the EOModel ==
39
40 To create the database, we will first create a EOModel and use migrations to build the database on the file system (H2 will take care of creating the database file).
41
42 An EOModel consists of entities, attributes and relationships. When using it in a RDBMS context, an entity is a table (or a view), an attribute is a table column and a relationship is a join between two tables.
43
44 To create the EOModel, in the project right-click on the project name and select **New** > **EOModel**.
45
46 Name it **BlogModel** and in the plugin list, select **H2**. Click **Finish**.
47
48 The model should show up in a window that looks like this:
49
50 If it didn't show up, the window might have opened behind the main Eclipse window. If that's the case, open the **Window** menu and select the windows that have //Entity Modeler// in its name.
51
52 In the Entity Modeler window, click on **Default**, and for the **URL** field, type {{code}}jdbc:h2:~/BlogTutorial{{/code}}. When the database will be created, it will be stored in your home directory (/Users/youruser/ on OS X).
53
54 Now, right-click on **BlogModel** and select **New Entity**.
55
56 Type the following details in the **Basic** tab:
57
58 * **Name**: BlogEntry
59 * **Table Name**: BlogEntry
60 * **Class Name**: your.app.model.BlogEntry
61
62 Now, it's time to add the entity's attributes (aka, the table's columns). You will see that the entity already have an attributed named "id". That attribute is a integer for the primary key. Leave it there.
63
64 Let's create the first attribute: the title of the blog entry. Right-click on the entity and select **New Attribute**. Type the following values:
65
66 * **Name**: title
67 * **Column**: title
68 * **Prototype**: varchar255
69
70 When you use prototypes, you don't need to define the type (varchar, int, etc.) for the database, so by using prototypes, if you switch from a RDBMS system to another one, say from H2 to MySQL, you only need to change the JDBC connection string and bundle the EOF plugin for the RDBMS, no need to switch data types in the model.
71
72 Now, repeat the last two steps to create the other attributes for the **BlogEntry** entity, with the following values:
73
74 |= Attribute name |= Column |= Prototype
75 | content | content | longtext
76 | creationDate | creationDate | dateTime
77
78 If you did everything well, the list of attributes should look like this:
79
80 You will notice that the attributes have a column with a lock in it. When a lock is present, it will use the value of that attribute for //UPDATE ... WHERE attribute = ''// statement. This is to do optimistic locking, aka to prevent data conflict when the data object was modified by two different users. Using timestamps for optimistic locking is not a good idea because for certain RDBMS, the value can be different because of milliseconds, so remove the locks on the **lastModified** and **creationDate** attributes. The final list should look like this:
81
82 Next step is to create the **Author** entity. Create a new entity with **Author** at its name (and also as the table name), and for the class name, use **your.app.model.Author**. The attributes for this entity are:
83
84 |= Attribute name |= Column |= Prototype
85 | firstName | firstName | varchar50
86 | lastName | lastName | varchar50
87 | email | email | varchar100
88
89 Final list of attributes should look like this:
90
91 Now, it's time to link the two entities together. A Author can have multiple blog entries, and a BlogEntry can only have one author. To create the relationship (the join), right-click on **Author** and select **New Relationship**. On your right, select **BlogEntry** in the list. On your left, select **to many BlogEntries**, and on your left, select **to one Author**. Now, in BlogEntry, we need to store the primary key of the author so that we can make the join. The relationship builder allow us to add that attribute, so make sure **and a new foreign key named** is checked (it is checked by default). The **Create Relationship** pane should look like this:
92
93 If you check in the **Outline** tab, you should see that **Author** now have a **blogEntries** relationship, and **BlogEntry** have a **author** relationship.
94
95 You are now ready to save the model. Save it (File > Save) and close the **Entity Modeler** window. If you open the **Sources** in the main Eclipse window, you will notice that the **Sources** folder contains a package named **your.app.model**.
96
97 That package have four Java classes: **Author**, **Author**, **BlogEntry** and **BlogEntry**. Those classes were generated by Veogen, a templating engine build on Velocity. The two classes that starts with a underscore are recreated every time you change the EOModel, so if you want to change something in those classes, you need to change the template (no need for that right now). But you can change freely the two classes that don't have the underscore, and this is what we will be doing.
98
99 What we are going to do is to write a simple method that returns the full name of an author, e.g. a method that simply concatenate the first name, a space and the last name of the author. To do so, double-click on **Author.java** and add the following methods:
100
101 {{code}}
102
103 public String fullName() {
104 return this.firstName() + " " + this.lastName();
105 }
106
107 {{/code}}
108
109 Nothing fancy here. Now open **BlogEntry.java** and add the following method:
110
111 {{code}}
112
113 @Override
114 public void awakeFromInsertion(EOEditingContext editingContext) {
115 super.awakeFromInsertion(editingContext);
116 this.setCreationDate(new NSTimestamp());
117 }
118
119 {{/code}}
120
121 Why are we adding this? **awakeFromInsertion** is a very good way of setting default values when creating a new instance of a Enterprise Object (EO). In this case, we want to set automatically the creation date without having the user to add that value.
122
123 Now, let's use migrations to actually create the database.
124
125 == Using migrations ==
126
127 Migrations allow you to create the tables and columns (and some types of constraint). **Entity Modeler** have support to generate the code for the first migration, which is called "migration 0". To do that, open the EOModel (**BlogModel EOModel** in the **Resources** folder), right-click on the model name and select **Generate Migration**.
128
129 Copy the generated code in the clipboard. Close **Entity Modeler** and in the main Eclipse window, right-click on **Sources**, select **New** and select **Class**.
130
131 Type **your.app.model.migrations** as the package and **BlogModel0** as the name of the class. Click **Finish**.
132
133 In the **Sources** folder, open the **your.app.model.migrations** package, a class named **BlogModel0** should be there. Delete everything in that file **EXCEPT** the first line (which should be //package your.app.model.migrations//) and paste the code that was generated by **Entity Modeler**. Save the file.
134
135 One last step: migrations are disabled by default. To enable them, you need to uncomment two properties in the **Properties** file that is located in the **Resources** folder. Open that file (double-click on it).
136
137 Remove the pound char in front of those two properties:
138
139 {{code}}
140
141 #er.migration.migrateAtStartup=true
142 #er.migration.createTablesIfNecessary=true
143
144 {{/code}}
145
146 After removing the pound char, the two properties should look like this:
147
148 {{code}}
149
150 er.migration.migrateAtStartup=true
151 er.migration.createTablesIfNecessary=true
152
153 {{/code}}
154
155 You are now ready to start the application so that it creates the database To do so, right-click on **Application.java** (in the **your.app** folder) and select **Run As** > **WOApplication**. In Eclipse's Console tab, you should see some output, including something similar to:
156
157 {{code}}
158
159 BlogRest[62990] INFO er.extensions.migration.ERXMigrator - Upgrading BlogModel to version 0 with migration 'your.app.model.migrations.BlogModel0@4743bf3d'
160 BlogRest[62990] INFO er.extensions.jdbc.ERXJDBCUtilities - Executing CREATE TABLE Author(email VARCHAR(100) NOT NULL, firstName VARCHAR(50) NOT NULL, id INTEGER NOT NULL, lastName VARCHAR(50) NOT NULL)
161 BlogRest[62990] INFO er.extensions.jdbc.ERXJDBCUtilities - Executing ALTER TABLE Author ADD PRIMARY KEY (id)
162 BlogRest[62990] INFO er.extensions.jdbc.ERXJDBCUtilities - Executing CREATE TABLE BlogEntry(authorID INTEGER NOT NULL, content TIMESTAMP NOT NULL, creationDate TIMESTAMP NOT NULL, id INTEGER NOT NULL, title VARCHAR(255) NOT NULL)
163 BlogRest[62990] INFO er.extensions.jdbc.ERXJDBCUtilities - Executing ALTER TABLE BlogEntry ADD PRIMARY KEY (id)
164 BlogRest[62990] INFO er.extensions.jdbc.ERXJDBCUtilities - Executing ALTER TABLE BlogEntry ADD CONSTRAINT "FOREIGN_KEY_BLOGENTRY_AUTHORID_AUTHOR_ID" FOREIGN KEY (authorID) REFERENCES Author (id)
165 BlogRest[62990] DEBUG NSLog - evaluateExpression: <er.h2.jdbcadaptor.ERH2PlugIn$H2Expression: "UPDATE _dbupdater SET version = ? WHERE modelname = ?" withBindings: 1:0(version), 2:"BlogModel"(modelName)>
166
167 {{/code}}
168
169 If you see this and that the application is running (it should open a window in your favorite browser), migration worked and your database have been created, congratulations You can now stop the application (click the square red button in Eclipse's Console tab) and continue to the next step.
170
171 = Creating REST controllers and routes =
172
173 Project Wonder contains a framework called ERRest, which follow the same patterns as Ruby on Rails REST concepts. Using REST-style URLs is perfect for building a public blog and to create REST services to manage posting over HTTP with JSON, XML or other formats.
174
175 By default, a REST route in ERRest will generate a link like this:
176
177 {{code}}
178 /cgi-bin/WebObjects/AppName.woa/ra/EntityName/id
179 {{/code}}
180
181 So for our case, to get the first blog posting from BlogRest, the URL will look like this:
182
183 {{code}}
184 /cgi-bin/WebObjects/BlogRest.woa/ra/blogEntries/1.html
185 {{/code}}
186
187 {{info}}
188 You can shorten the URL by using mod_rewrite in Apache httpd
189 {{/info}}
190
191 .
192
193 == Creating controllers ==
194
195 ERRest needs controllers to act as a broker between working with the objects and the routes. So let's create a controller for BlogEntry.
196
197 Create a Java class named **BlogEntryController**, in the **your.app.rest.controllers** package, that will extend from **er.rest.routes.ERXDefaultRouteController**. Click **Finish**.
198
199 When you extend from **ERXDefaultRouteController**, a bunch of methods are added to the subclass. Let's see what they are for.
200
201 * **updateAction**: to update a specific instance of BlogEntry
202 * **destroyAction**: to delete a specific instance of BlogEntry
203 * **showAction**: to get one specific instance of BlogEntry
204 * **createAction**: to create a new object (a new instance of BlogEntry)
205 * **indexAction**: to list all (or a sublist) of the objects.
206
207 {{info}}
208 In Project Wonder, *Action* at the end of a method is a convention for REST and Direct Actions, when you call those methods from certain components, you don't need to add the *Action* part.
209 {{/info}}
210
211 For this tutorial, we will implement the **createAction** and **showAction** methods. But first, we need to create a key filter. A key filter will... filter the input and the output of REST request so that you don't have to send all attributes for a blog entry. For example, we want to show the details for an author, but we don't want to show the password for the author (in real-life, the password would be encrypted)!
212
213 Add this method in **BlogEntryController**:
214
215 {{code}}
216
217 protected ERXKeyFilter filter() {
218 ERXKeyFilter personFilter = ERXKeyFilter.filterWithAttributes();
219 personFilter.setAnonymousUpdateEnabled(true);
220
221 ERXKeyFilter filter = ERXKeyFilter.filterWithAttributes();
222 filter.include(BlogEntry.AUTHOR, personFilter);
223 filter.setUnknownKeyIgnored(true);
224
225 return filter;
226 }
227
228 {{/code}}
229
230 Now, let's implement the **creationAction** method:
231
232 {{code}}
233
234 public WOActionResults createAction() throws Throwable {
235 BlogEntry entry = create(filter());
236 editingContext().saveChanges();
237 return response(entry, filter());
238 }
239
240 {{/code}}
241
242 In 3 lines of code, you can create an object based on the request, save the new object to the database and return the new object in the response. Not bad, eh?
243
244 Last step in the controller: implementing the **showAction** method. Again, the code is simple:
245
246 {{code}}
247
248 public WOActionResults indexAction() throws Throwable {
249 NSArray<BlogEntry> entries = BlogEntry.fetchAllBlogEntries(editingContext());
250 return response(entries, filter());
251 }
252
253 {{/code}}
254
255 That code simply fetch all blog entries and return them in the response.
256
257 We can now go to the next step: adding the routes.
258
259 == Adding the routes ==
260
261 A route in ERRest is simply a way to define the URL for the entities and to specify which controller the route should use. When your controller extends from **ERXDefaultRouteController**, it's easy to register a controller and a route. In **Application.java**, in the **Application** constructor, add the following code:
262
263 {{code}}
264
265 ERXRouteRequestHandler restRequestHandler = new ERXRouteRequestHandler();
266 restRequestHandler.addDefaultRoutes(BlogEntry.ENTITY_NAME);
267 ERXRouteRequestHandler.register(restRequestHandler);
268 setDefaultRequestHandler(restRequestHandler);
269
270 {{/code}}
271
272 The **addDefaultRoutes** method do all of the required magic, and use convention. That's why we had to name the controller **BlogEntryController**, because the convention is <EntityName>Controller.
273
274 We are now reading to add and list blog postings! Start the application and take notice of the URL. It should be something like //http:~/~/yourip:someport/cgi-bin/WebObjects/BlogRest.woa//
275
276 == Adding posts and authors with curl ==
277
278 Since we didn't implement any HTML for our REST routes, we will create blog entries with //curl//, an open source HTTP client that is bundled with Mac OS X (you can use another client, like wget, if you like too). So let's create a blog entry.
279
280 To create a blog entry, you need to use the POST HTTP method. We will use JSON as the format since it's a bit less chatty than XML. So if the URL to the application is //http:~/~/192.168.0.102:52406/cgi-bin/WebObjects/BlogRest.woa_, the full //curl// command will be~://
281
282 {{code}}
283 curl -X POST -v -d '{ "title": "First post", "content": "Some text", "author": { "firstName": "Pascal", "lastName": "Robert", "email": "probert@macti.ca" } }' http://192.168.0.102:52406/cgi-bin/WebObjects/BlogRest.woa/ra/blogEntries.json
284 {{/code}}
285
286 The response should look this:
287
288 {{code}}
289
290 HTTP/1.0 201 Apple WebObjects
291 Content-Length: 249
292 x-webobjects-loadaverage: 0
293 Content-Type: application/json
294
295 {"id":1,"type":"BlogEntry","content":"Some text","creationDate":"2011-12-27T21:59:08Z","title":"First post","author":{"id":1,"type":"Author","email":"probert@macti.ca","firstName":"Pascal","lastName":"Robert"}}
296
297 {{/code}}
298
299 To get a list of blog entries:
300
301 {{code}}
302
303 curl -X GET http://192.168.0.102:52406/cgi-bin/WebObjects/BlogRest.woa/ra/blogEntries.json
304
305 {{/code}}
306
307 == Adding HTML views for blog posts ==