Changes for page Your First Rest Project

Last modified by Steve Peery on 2013/09/06 11:02

From version 20.1
edited by skcodes
on 2013/05/13 12:53
Change comment: Migrated to Confluence 4.0
To version 11.1
edited by Pascal Robert
on 2011/12/27 22:21
Change comment: There is no comment for this version

Summary

Details

Page properties
Author
... ... @@ -1,1 +1,1 @@
1 -XWiki.skcodes
1 +XWiki.probert
Content
... ... @@ -1,4 +1,4 @@
1 -{{toc/}}
1 +{{toc}}{{/toc}}
2 2  
3 3  = Introduction =
4 4  
... ... @@ -20,93 +20,20 @@
20 20  
21 21  BlogEntry will have the following columns:
22 22  
23 -|=(((
24 -Column name
25 -)))|=(((
26 -Type
27 -)))|=(((
28 -Constraints
29 -)))
30 -|(((
31 -id
32 -)))|(((
33 -integer
34 -)))|(((
35 -primary key
36 -)))
37 -|(((
38 -title
39 -)))|(((
40 -string(255)
41 -)))|(((
42 -
43 -)))
44 -|(((
45 -content
46 -)))|(((
47 -string(4000)
48 -)))|(((
49 -
50 -)))
51 -|(((
52 -creationDate
53 -)))|(((
54 -timestamp
55 -)))|(((
56 -
57 -)))
58 -|(((
59 -lastModified
60 -)))|(((
61 -timestamp
62 -)))|(((
63 -
64 -)))
65 -|(((
66 -author
67 -)))|(((
68 -integer
69 -)))|(((
70 -relation with Author
71 -)))
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
72 72  
73 73  Author will have the following columns:
74 74  
75 -|=(((
76 -Column name
77 -)))|=(((
78 -Type
79 -)))|=(((
80 -Constraints
81 -)))
82 -|(((
83 -id
84 -)))|(((
85 -integer
86 -)))|(((
87 -primary key
88 -)))
89 -|(((
90 -firstName
91 -)))|(((
92 -string(50)
93 -)))|(((
94 -
95 -)))
96 -|(((
97 -lastName
98 -)))|(((
99 -string(50)
100 -)))|(((
101 -
102 -)))
103 -|(((
104 -email
105 -)))|(((
106 -string(100)
107 -)))|(((
108 -unique
109 -)))
32 +|= Column name |= Type |= Constraints
33 +| id | integer | primary key
34 +| firstName | string(50) |
35 +| lastName | string(50) |
36 +| email | string(100) | unique
110 110  
111 111  == Creating the EOModel ==
112 112  
... ... @@ -114,7 +114,7 @@
114 114  
115 115  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.
116 116  
117 -To create the EOModel, in the project right-click on the project name and select **New** -> **EOModel**.
44 +To create the EOModel, in the project right-click on the project name and select **New** > **EOModel**.
118 118  
119 119  Name it **BlogModel** and in the plugin list, select **H2**. Click **Finish**.
120 120  
... ... @@ -122,14 +122,8 @@
122 122  
123 123  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.
124 124  
125 -In the Entity Modeler window, click on **Default**, and for the **URL** field, type
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).
126 126  
127 -{{code}}
128 -jdbc:h2:~/BlogTutorial
129 -{{/code}}
130 -
131 -. When the database will be created, it will be stored in your home directory (/Users/youruser/ on OS X).
132 -
133 133  Now, right-click on **BlogModel** and select **New Entity**.
134 134  
135 135  Type the following details in the **Basic** tab:
... ... @@ -150,79 +150,30 @@
150 150  
151 151  Now, repeat the last two steps to create the other attributes for the **BlogEntry** entity, with the following values:
152 152  
153 -|=(((
154 -Attribute name
155 -)))|=(((
156 -Column
157 -)))|=(((
158 -Prototype
159 -)))
160 -|(((
161 -content
162 -)))|(((
163 -content
164 -)))|(((
165 -longtext
166 -)))
167 -|(((
168 -creationDate
169 -)))|(((
170 -creationDate
171 -)))|(((
172 -dateTime
173 -)))
174 -|(((
175 -lastModified
176 -)))|(((
177 -lastModified
178 -)))|(((
179 -dateTime
180 -)))
74 +|= Attribute name |= Column |= Prototype
75 +| content | content | longtext
76 +| creationDate | creationDate | dateTime
181 181  
182 182  If you did everything well, the list of attributes should look like this:
183 183  
184 -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 **creationDate** attribute. The final list should look like this:
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:
185 185  
186 186  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:
187 187  
188 -|=(((
189 -Attribute name
190 -)))|=(((
191 -Column
192 -)))|=(((
193 -Prototype
194 -)))
195 -|(((
196 -firstName
197 -)))|(((
198 -firstName
199 -)))|(((
200 -varchar50
201 -)))
202 -|(((
203 -lastName
204 -)))|(((
205 -lastName
206 -)))|(((
207 -varchar50
208 -)))
209 -|(((
210 -email
211 -)))|(((
212 -email
213 -)))|(((
214 -varchar100
215 -)))
84 +|= Attribute name |= Column |= Prototype
85 +| firstName | firstName | varchar50
86 +| lastName | lastName | varchar50
87 +| email | email | varchar100
216 216  
217 217  Final list of attributes should look like this:
218 218  
219 -Now, it's time to link the two entities together. An 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 right, 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:
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:
220 220  
221 221  If you check in the **Outline** tab, you should see that **Author** now have a **blogEntries** relationship, and **BlogEntry** have a **author** relationship.
222 222  
223 -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**. (If this folder doesn't appear, you may need to set your preferences to automatically generate these source files; see the second suggestion on [[http:~~/~~/wiki.wocommunity.org/display/documentation/Useful+Eclipse+or+WOLips+Preferences>>url:http://wiki.wocommunity.org/display/documentation/Useful+Eclipse+or+WOLips+Preferences||rel="nofollow" shape="rect" class="external-link"]].)
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**.
224 224  
225 -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.
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.
226 226  
227 227  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:
228 228  
... ... @@ -240,21 +240,19 @@
240 240  
241 241   @Override
242 242   public void awakeFromInsertion(EOEditingContext editingContext) {
243 - super.awakeFromInsertion(editingContext);
244 - NSTimestamp now = new NSTimestamp();
245 - setCreationDate(now);
246 - setLastModified(now);
115 + super.awakeFromInsertion(editingContext);
116 + this.setCreationDate(new NSTimestamp());
247 247   }
248 248  
249 249  {{/code}}
250 250  
251 -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 and last modification dates without having the user to add those values.
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.
252 252  
253 253  Now, let's use migrations to actually create the database.
254 254  
255 255  == Using migrations ==
256 256  
257 -Migrations allow you to create the tables and columns (and some types of constraint). **Entity Modeler** has 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**.
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**.
258 258  
259 259  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**.
260 260  
... ... @@ -282,7 +282,7 @@
282 282  
283 283  {{/code}}
284 284  
285 -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:
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:
286 286  
287 287  {{code}}
288 288  
... ... @@ -296,7 +296,7 @@
296 296  
297 297  {{/code}}
298 298  
299 -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.
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.
300 300  
301 301  = Creating REST controllers and routes =
302 302  
... ... @@ -318,6 +318,8 @@
318 318  You can shorten the URL by using mod_rewrite in Apache httpd
319 319  {{/info}}
320 320  
191 +.
192 +
321 321  == Creating controllers ==
322 322  
323 323  ERRest needs controllers to act as a broker between working with the objects and the routes. So let's create a controller for BlogEntry.
... ... @@ -333,16 +333,16 @@
333 333  * **indexAction**: to list all (or a sublist) of the objects.
334 334  
335 335  {{info}}
336 -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.
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.
337 337  {{/info}}
338 338  
339 -For this tutorial, we will implement the **createAction** and **indexAction** 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)!
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)!
340 340  
341 341  Add this method in **BlogEntryController**:
342 342  
343 343  {{code}}
344 344  
345 -protected ERXKeyFilter filter() {
217 + protected ERXKeyFilter filter() {
346 346   ERXKeyFilter personFilter = ERXKeyFilter.filterWithAttributes();
347 347   personFilter.setAnonymousUpdateEnabled(true);
348 348  
... ... @@ -355,11 +355,11 @@
355 355  
356 356  {{/code}}
357 357  
358 -Now, let's implement the **createAction** method:
230 +Now, let's implement the **creationAction** method:
359 359  
360 360  {{code}}
361 361  
362 -public WOActionResults createAction() throws Throwable {
234 + public WOActionResults createAction() throws Throwable {
363 363   BlogEntry entry = create(filter());
364 364   editingContext().saveChanges();
365 365   return response(entry, filter());
... ... @@ -369,11 +369,11 @@
369 369  
370 370  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?
371 371  
372 -Last step in the controller: implementing the **indexAction** method. Again, the code is simple:
244 +Last step in the controller: implementing the **showAction** method. Again, the code is simple:
373 373  
374 374  {{code}}
375 375  
376 -public WOActionResults indexAction() throws Throwable {
248 + public WOActionResults indexAction() throws Throwable {
377 377   NSArray<BlogEntry> entries = BlogEntry.fetchAllBlogEntries(editingContext());
378 378   return response(entries, filter());
379 379   }
... ... @@ -390,7 +390,7 @@
390 390  
391 391  {{code}}
392 392  
393 -ERXRouteRequestHandler restRequestHandler = new ERXRouteRequestHandler();
265 + ERXRouteRequestHandler restRequestHandler = new ERXRouteRequestHandler();
394 394   restRequestHandler.addDefaultRoutes(BlogEntry.ENTITY_NAME);
395 395   ERXRouteRequestHandler.register(restRequestHandler);
396 396   setDefaultRequestHandler(restRequestHandler);
... ... @@ -397,15 +397,15 @@
397 397  
398 398  {{/code}}
399 399  
400 -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.
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.
401 401  
402 -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_>>url:http://yourip:someport/cgi-bin/WebObjects/BlogRest.woa_||shape="rect"]]
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//
403 403  
404 404  == Adding posts and authors with curl ==
405 405  
406 406  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.
407 407  
408 -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_>>url:http://192.168.0.102:52406/cgi-bin/WebObjects/BlogRest.woa_||shape="rect"]], the full _curl// command will be:
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~://
409 409  
410 410  {{code}}
411 411  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
... ... @@ -432,133 +432,4 @@
432 432  
433 433  {{/code}}
434 434  
435 -You can stop the application and proceed to the next step.
436 -
437 437  == Adding HTML views for blog posts ==
438 -
439 -Now, let's build a HTML view for blog posts (you don't want your readers to get your posts by JSON, right?). Again, we will use convention to make it work easily. Open up **BlogEntryController** and add the following method:
440 -
441 -{{code}}
442 -
443 -@Override
444 - protected boolean isAutomaticHtmlRoutingEnabled() {
445 - return true;
446 - }
447 -
448 -{{/code}}
449 -
450 -Switching the return value of this method says that we will follow a certain convention for HTML components. The convention for automatic HTML routing is that the component should be named <EntityName><Action>Page.wo. So in our case, the component will be **BlogEntryIndexPage**. Right-click on the project name in Eclipse and select **New** -> **WOComponent**. Change the name to **BlogEntryIndexPage** and check the **Create HTML contents** button. Click **Finish**.
451 -
452 -The next step to get it to work is to make **BlogEntryIndexPage** to implement the **er.rest.routes.IERXRouteComponent** interface.
453 -
454 -{{code}}
455 -
456 -import er.rest.routes.IERXRouteComponent;
457 -
458 -public class BlogEntryIndexPage extends WOComponent implements IERXRouteComponent {
459 -
460 -{{/code}}
461 -
462 -So now, the automatic HTML routing will send the request for **ra/blogEntries.html** to the **BlogEntryIndexPage** component. But we don't have any content in this component, so let's make a method to fetch all blog entries per creation date in descending order. So in **BlogEntryIndexPage.java**, add the following method:
463 -
464 -{{code}}
465 -
466 -public NSArray<BlogEntry> entries() {
467 - EOEditingContext ec = ERXEC.newEditingContext();
468 - return BlogEntry.fetchAllBlogEntries(ec, BlogEntry.CREATION_DATE.descs());
469 - }
470 -
471 -{{/code}}
472 -
473 -We need to use that method in a WORepetition, and for that loop, we need a BlogEntry variable to iterate in the list, so add the following code to **BlogEntryIndexPage.java**:
474 -
475 -{{code}}
476 -
477 -private BlogEntry entryItem;
478 -
479 - public BlogEntry entryItem() {
480 - return entryItem;
481 - }
482 -
483 - public void setEntryItem(BlogEntry entryItem) {
484 - this.entryItem = entryItem;
485 - }
486 -
487 -{{/code}}
488 -
489 -The Java part is done, so let's add the loop inside the component. Open **BlogEntryIndexPage.wo** (it's located in the **Component** folder) and right after the <body> tag, add:
490 -
491 -{{code}}
492 -
493 -<wo:loop list="$entries" item="$entryItem">
494 - <p><wo:str value="$entryItem.title" /></p>
495 - <p><wo:str value="$entryItem.author.fullName" /></p>
496 - </wo:loop>
497 -
498 -{{/code}}
499 -
500 -That component code will loop over the blog entries and display the title of the entry + the name of the author. Save everything and run the application.
501 -
502 -If you go to [[http:~~/~~/192.168.0.102:52406/cgi-bin/WebObjects/BlogRest.woa/ra/blogEntries.html>>url:http://192.168.0.102:52406/cgi-bin/WebObjects/BlogRest.woa/ra/blogEntries.html||shape="rect"]], you will see the list of blog entries!
503 -
504 -Now that we have a list of blog entries, let's make a page to show the content of a blog entry. Create a new component named **BlogEntryShowPage**.
505 -
506 -Open **BlogEntryShowPage.java** and make sure the class implements **er.rest.routes.IERXRouteComponent**.
507 -
508 -{{code}}
509 -
510 -import er.rest.routes.IERXRouteComponent;
511 -
512 -public class BlogEntryShowPage extends WOComponent implements IERXRouteComponent {
513 -
514 -{{/code}}
515 -
516 -We need to add other methods to receive the BlogEntry object from the controller. In **BlogEntryShowPage.java**, add:
517 -
518 -{{code}}
519 -
520 -private BlogEntry blogEntry;
521 -
522 - @ERXRouteParameter
523 - public void setBlogEntry(BlogEntry blogEntryFromController) {
524 - this.blogEntry = blogEntryFromController;
525 - }
526 -
527 - public BlogEntry blogEntry() {
528 - return this.blogEntry;
529 - }
530 -
531 -{{/code}}
532 -
533 -The **@ERXRouteParameter** annotation tells the REST framework that it can automatically receive an object from the controller. And again, it's convention at work. You have to use the annotation and the setter name should be //set<EntityName>//, so for a BlogEntry, it's //setBlogEntry//, for a Author, it will be //setAuthor//.
534 -
535 -The Java part of the work is done, so save the Java class. It's time to work on the component part. Open **BlogEntryShowPage.wo** and between the <body></body> part, add:
536 -
537 -{{code}}
538 -
539 -<h1><wo:str value="$blogEntry.title" /></h1>
540 - <p><wo:str value="$blogEntry.content" /></p>
541 - <p>Created on: <wo:str value="$blogEntry.creationDate" dateformat="%Y/%m/%d" /></p>
542 - <p>Added by: <wo:str value="$blogEntry.author.fullName" /></p>
543 -
544 -{{/code}}
545 -
546 -Our view component is done, the only thing remaining is a link for the blog entry list (BlogEntryIndexPage) to the view page (BlogEntryShowPage). Save **BlogEntryShowPage.wo** and open **BlogEntryIndexPage.wo**. We are going to add a link on the title, you will replace to replace this:
547 -
548 -{{code}}
549 -
550 -<p><wo:str value="$entryItem.title" /></p>
551 -
552 -{{/code}}
553 -
554 -with:
555 -
556 -{{code}}
557 -
558 -<p><wo:ERXRouteLink entityName="BlogEntry" record="$entryItem" action="show"><wo:str value="$entryItem.title" /></wo:ERXRouteLink></p>
559 -
560 -{{/code}}
561 -
562 -Save the component and run the app. Go to [[http:~~/~~/192.168.0.102:52406/cgi-bin/WebObjects/BlogRest.woa/ra/blogEntries.html>>url:http://192.168.0.102:52406/cgi-bin/WebObjects/BlogRest.woa/ra/blogEntries.html||shape="rect"]] to get the list of posts, and you should see a link on the title. Click on it, and now you get the full details of the blog entry!
563 -
564 -The REST part of this tutorial is now complete, [[you can now move to the next part of the tutorial>>doc:Your First Framework]].