Changes for page Your First Rest Project
Last modified by Steve Peery on 2013/09/06 11:02
From version 24.1
edited by steffan
on 2013/02/10 18:44
on 2013/02/10 18:44
Change comment:
Fix validation error when POSTing a blog entry by setting lastModified value
To version 11.1
edited by Pascal Robert
on 2011/12/27 22:21
on 2011/12/27 22:21
Change comment:
There is no comment for this version
Summary
-
Page properties (2 modified, 0 added, 0 removed)
Details
- Page properties
-
- Author
-
... ... @@ -1,1 +1,1 @@ 1 -XWiki. steffan1 +XWiki.probert - Content
-
... ... @@ -25,7 +25,6 @@ 25 25 | title | string(255) | 26 26 | content | string(4000) | 27 27 | creationDate | timestamp | 28 -| lastModified | timestamp | 29 29 | author | integer | relation with Author 30 30 31 31 Author will have the following columns: ... ... @@ -75,11 +75,10 @@ 75 75 |= Attribute name |= Column |= Prototype 76 76 | content | content | longtext 77 77 | creationDate | creationDate | dateTime 78 -| lastModified | lastModified | dateTime 79 79 80 80 If you did everything well, the list of attributes should look like this: 81 81 82 -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: 83 83 84 84 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: 85 85 ... ... @@ -90,7 +90,7 @@ 90 90 91 91 Final list of attributes should look like this: 92 92 93 -Now, it's time to link the two entities together. A nAuthor 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 yourright, 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: 94 94 95 95 If you check in the **Outline** tab, you should see that **Author** now have a **blogEntries** relationship, and **BlogEntry** have a **author** relationship. 96 96 ... ... @@ -114,21 +114,19 @@ 114 114 115 115 @Override 116 116 public void awakeFromInsertion(EOEditingContext editingContext) { 117 - super.awakeFromInsertion(editingContext); 118 - NSTimestamp now = new NSTimestamp(); 119 - setCreationDate(now); 120 - setLastModified(now); 115 + super.awakeFromInsertion(editingContext); 116 + this.setCreationDate(new NSTimestamp()); 121 121 } 122 122 123 123 {{/code}} 124 124 125 -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 andlastmodification dateswithout having the user to add thosevalues.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. 126 126 127 127 Now, let's use migrations to actually create the database. 128 128 129 129 == Using migrations == 130 130 131 -Migrations allow you to create the tables and columns (and some types of constraint). **Entity Modeler** ha ssupport 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**. 132 132 133 133 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**. 134 134 ... ... @@ -192,6 +192,8 @@ 192 192 You can shorten the URL by using mod_rewrite in Apache httpd 193 193 {{/info}} 194 194 191 +. 192 + 195 195 == Creating controllers == 196 196 197 197 ERRest needs controllers to act as a broker between working with the objects and the routes. So let's create a controller for BlogEntry. ... ... @@ -210,13 +210,13 @@ 210 210 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. 211 211 {{/info}} 212 212 213 -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)! 214 214 215 215 Add this method in **BlogEntryController**: 216 216 217 217 {{code}} 218 218 219 -protected ERXKeyFilter filter() { 217 + protected ERXKeyFilter filter() { 220 220 ERXKeyFilter personFilter = ERXKeyFilter.filterWithAttributes(); 221 221 personFilter.setAnonymousUpdateEnabled(true); 222 222 ... ... @@ -229,11 +229,11 @@ 229 229 230 230 {{/code}} 231 231 232 -Now, let's implement the **creat eAction** method:230 +Now, let's implement the **creationAction** method: 233 233 234 234 {{code}} 235 235 236 -public WOActionResults createAction() throws Throwable { 234 + public WOActionResults createAction() throws Throwable { 237 237 BlogEntry entry = create(filter()); 238 238 editingContext().saveChanges(); 239 239 return response(entry, filter()); ... ... @@ -243,11 +243,11 @@ 243 243 244 244 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? 245 245 246 -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: 247 247 248 248 {{code}} 249 249 250 -public WOActionResults indexAction() throws Throwable { 248 + public WOActionResults indexAction() throws Throwable { 251 251 NSArray<BlogEntry> entries = BlogEntry.fetchAllBlogEntries(editingContext()); 252 252 return response(entries, filter()); 253 253 } ... ... @@ -264,7 +264,7 @@ 264 264 265 265 {{code}} 266 266 267 -ERXRouteRequestHandler restRequestHandler = new ERXRouteRequestHandler(); 265 + ERXRouteRequestHandler restRequestHandler = new ERXRouteRequestHandler(); 268 268 restRequestHandler.addDefaultRoutes(BlogEntry.ENTITY_NAME); 269 269 ERXRouteRequestHandler.register(restRequestHandler); 270 270 setDefaultRequestHandler(restRequestHandler); ... ... @@ -271,15 +271,15 @@ 271 271 272 272 {{/code}} 273 273 274 -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. 275 275 276 -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>>http://yourip:someport/cgi-bin/WebObjects/BlogRest.woa_]]//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// 277 277 278 278 == Adding posts and authors with curl == 279 279 280 280 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. 281 281 282 -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>>http://192.168.0.102:52406/cgi-bin/WebObjects/BlogRest.woa_]], 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~:// 283 283 284 284 {{code}} 285 285 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 ... ... @@ -306,133 +306,4 @@ 306 306 307 307 {{/code}} 308 308 309 -You can stop the application and proceed to the next step. 310 - 311 311 == Adding HTML views for blog posts == 312 - 313 -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: 314 - 315 -{{code}} 316 - 317 -@Override 318 - protected boolean isAutomaticHtmlRoutingEnabled() { 319 - return true; 320 - } 321 - 322 -{{/code}} 323 - 324 -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**. 325 - 326 -The next step to get it to work is to make **BlogEntryIndexPage** to implement the **er.rest.routes.IERXRouteComponent** interface. 327 - 328 -{{code}} 329 - 330 -import er.rest.routes.IERXRouteComponent; 331 - 332 -public class BlogEntryIndexPage extends WOComponent implements IERXRouteComponent { 333 - 334 -{{/code}} 335 - 336 -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: 337 - 338 -{{code}} 339 - 340 -public NSArray<BlogEntry> entries() { 341 - EOEditingContext ec = ERXEC.newEditingContext(); 342 - return BlogEntry.fetchAllBlogEntries(ec, BlogEntry.CREATION_DATE.descs()); 343 - } 344 - 345 -{{/code}} 346 - 347 -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**: 348 - 349 -{{code}} 350 - 351 -private BlogEntry entryItem; 352 - 353 - public BlogEntry entryItem() { 354 - return entryItem; 355 - } 356 - 357 - public void setEntryItem(BlogEntry entryItem) { 358 - this.entryItem = entryItem; 359 - } 360 - 361 -{{/code}} 362 - 363 -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: 364 - 365 -{{code}} 366 - 367 -<wo:loop list="$entries" item="$entryItem"> 368 - <p><wo:str value="$entryItem.title" /></p> 369 - <p><wo:str value="$entryItem.author.fullName" /></p> 370 - </wo:loop> 371 - 372 -{{/code}} 373 - 374 -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. 375 - 376 -If you go to [[http://192.168.0.102:52406/cgi-bin/WebObjects/BlogRest.woa/ra/blogEntries.html]], you will see the list of blog entries 377 - 378 -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**. 379 - 380 -Open **BlogEntryShowPage.java** and make sure the class implements **er.rest.routes.IERXRouteComponent**. 381 - 382 -{{code}} 383 - 384 -import er.rest.routes.IERXRouteComponent; 385 - 386 -public class BlogEntryShowPage extends WOComponent implements IERXRouteComponent { 387 - 388 -{{/code}} 389 - 390 -We need to add other methods to receive the BlogEntry object from the controller. In **BlogEntryShowPage.java**, add: 391 - 392 -{{code}} 393 - 394 -private BlogEntry blogEntry; 395 - 396 - @ERXRouteParameter 397 - public void setBlogEntry(BlogEntry blogEntryFromController) { 398 - this.blogEntry = blogEntryFromController; 399 - } 400 - 401 - public BlogEntry blogEntry() { 402 - return this.blogEntry; 403 - } 404 - 405 -{{/code}} 406 - 407 -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//. 408 - 409 -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: 410 - 411 -{{code}} 412 - 413 -<h1><wo:str value="$blogEntry.title" /></h1> 414 - <p><wo:str value="$blogEntry.content" /></p> 415 - <p>Created on: <wo:str value="$blogEntry.creationDate" dateformat="%Y/%m/%d" /></p> 416 - <p>Added by: <wo:str value="$blogEntry.author.fullName" /></p> 417 - 418 -{{/code}} 419 - 420 -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: 421 - 422 -{{code}} 423 - 424 -<p><wo:str value="$entryItem.title" /></p> 425 - 426 -{{/code}} 427 - 428 -with: 429 - 430 -{{code}} 431 - 432 -<p><wo:ERXRouteLink entityName="BlogEntry" record="$entryItem" action="show"><wo:str value="$entryItem.title" /></wo:ERXRouteLink></p> 433 - 434 -{{/code}} 435 - 436 -Save the component and run the app. Go to [[http://192.168.0.102:52406/cgi-bin/WebObjects/BlogRest.woa/ra/blogEntries.html]] 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 437 - 438 -The REST part of this tutorial is now complete, [[you can now move to the next part of the tutorial>>Your First Framework]].