Changes for page Your First Rest Project
Last modified by Steve Peery on 2013/09/06 11:02
From version 42.1
edited by Pascal Robert
on 2012/12/12 08:00
on 2012/12/12 08:00
Change comment:
There is no comment for this version
To version 46.1
edited by Filippo Laurìa
on 2013/07/22 12:55
on 2013/07/22 12:55
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.p robert1 +XWiki.filippolauria - Content
-
... ... @@ -1,5 +2,7 @@ 1 -{{toc}}{{/toc}} 2 2 2 + 3 +{{toc/}} 4 + 3 3 = Introduction = 4 4 5 5 In the first part of the Blog tutorial, you will learn: ... ... @@ -20,21 +20,93 @@ 20 20 21 21 BlogEntry will have the following columns: 22 22 23 -|= Column name |= Type |= Constraints 24 -| id | integer | primary key 25 -| title | string(255) | 26 -| content | string(4000) | 27 -| creationDate | timestamp | 28 -| lastModified | timestamp | 29 -| author | integer | relation with Author 25 +|=((( 26 +Column name 27 +)))|=((( 28 +Type 29 +)))|=((( 30 +Constraints 31 +))) 32 +|((( 33 +id 34 +)))|((( 35 +integer 36 +)))|((( 37 +primary key 38 +))) 39 +|((( 40 +title 41 +)))|((( 42 +string(255) 43 +)))|((( 44 + 45 +))) 46 +|((( 47 +content 48 +)))|((( 49 +string(4000) 50 +)))|((( 51 + 52 +))) 53 +|((( 54 +creationDate 55 +)))|((( 56 +timestamp 57 +)))|((( 58 + 59 +))) 60 +|((( 61 +lastModified 62 +)))|((( 63 +timestamp 64 +)))|((( 65 + 66 +))) 67 +|((( 68 +author 69 +)))|((( 70 +integer 71 +)))|((( 72 +relation with Author 73 +))) 30 30 31 31 Author will have the following columns: 32 32 33 -|= Column name |= Type |= Constraints 34 -| id | integer | primary key 35 -| firstName | string(50) | 36 -| lastName | string(50) | 37 -| email | string(100) | unique 77 +|=((( 78 +Column name 79 +)))|=((( 80 +Type 81 +)))|=((( 82 +Constraints 83 +))) 84 +|((( 85 +id 86 +)))|((( 87 +integer 88 +)))|((( 89 +primary key 90 +))) 91 +|((( 92 +firstName 93 +)))|((( 94 +string(50) 95 +)))|((( 96 + 97 +))) 98 +|((( 99 +lastName 100 +)))|((( 101 +string(50) 102 +)))|((( 103 + 104 +))) 105 +|((( 106 +email 107 +)))|((( 108 +string(100) 109 +)))|((( 110 +unique 111 +))) 38 38 39 39 == Creating the EOModel == 40 40 ... ... @@ -42,16 +42,24 @@ 42 42 43 43 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. 44 44 45 -To create the EOModel, in the project right-click on the project name and select **New** > **EOModel**. 119 +To create the EOModel, in the project right-click on the project name and select **New** -> **EOModel**. 46 46 47 47 Name it **BlogModel** and in the plugin list, select **H2**. Click **Finish**. 48 48 49 49 The model should show up in a window that looks like this: 50 50 125 +[[image:attach:EOModeler.png]] 126 + 51 51 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. 52 52 53 -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).129 +In the Entity Modeler window, click on **Default**, and for the **URL** field, type 54 54 131 +{{code}} 132 +jdbc:h2:~/BlogTutorial 133 +{{/code}} 134 + 135 +. When the database will be created, it will be stored in your home directory (/Users/youruser/ on OS X). 136 + 55 55 Now, right-click on **BlogModel** and select **New Entity**. 56 56 57 57 Type the following details in the **Basic** tab: ... ... @@ -72,35 +72,97 @@ 72 72 73 73 Now, repeat the last two steps to create the other attributes for the **BlogEntry** entity, with the following values: 74 74 75 -|= Attribute name |= Column |= Prototype 76 -| content | content | longtext 77 -| creationDate | creationDate | dateTime 157 +|=((( 158 +Attribute name 159 +)))|=((( 160 +Column 161 +)))|=((( 162 +Prototype 163 +))) 164 +|((( 165 +content 166 +)))|((( 167 +content 168 +)))|((( 169 +longtext 170 +))) 171 +|((( 172 +creationDate 173 +)))|((( 174 +creationDate 175 +)))|((( 176 +dateTime 177 +))) 178 +|((( 179 +lastModified 180 +)))|((( 181 +lastModified 182 +)))|((( 183 +dateTime 184 +))) 78 78 79 79 If you did everything well, the list of attributes should look like this: 80 80 188 +[[image:attach:list_wlock.png]] 189 + 81 81 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: 82 82 192 +[[image:attach:list.png]] 193 + 83 83 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: 84 84 85 -|= Attribute name |= Column |= Prototype 86 -| firstName | firstName | varchar50 87 -| lastName | lastName | varchar50 88 -| email | email | varchar100 196 +|=((( 197 +Attribute name 198 +)))|=((( 199 +Column 200 +)))|=((( 201 +Prototype 202 +))) 203 +|((( 204 +firstName 205 +)))|((( 206 +firstName 207 +)))|((( 208 +varchar50 209 +))) 210 +|((( 211 +lastName 212 +)))|((( 213 +lastName 214 +)))|((( 215 +varchar50 216 +))) 217 +|((( 218 +email 219 +)))|((( 220 +email 221 +)))|((( 222 +varchar100 223 +))) 89 89 90 90 Final list of attributes should look like this: 91 91 227 +[[image:attach:author_list.png]] 228 + 92 92 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: 93 93 231 +[[image:attach:relationship.png]] 232 + 94 94 If you check in the **Outline** tab, you should see that **Author** now have a **blogEntries** relationship, and **BlogEntry** have a **author** relationship. 95 95 96 - Youarenow readyto savethe model. Save it (File > Save) andclose the **Entity Modeler** window. If youopenthe **Sources** in the main Eclipse window, you will noticehat the **Sources** folder contains a package named **your.app.model**.235 +[[image:attach:outline_tab.png]] 97 97 98 - Thatpackage havefourJava classes:**Author**,**Author**, **BlogEntry**and**BlogEntry**.Thoseclassesweregeneratedby Veogen,atemplatingenginebuildnVelocity.The twoclassesthatstarts withaunderscorearerecreatedevery time youchange theEOModel,soifyouwant tochangeethingin those classes,you needto changethetemplate (noeedforthatrightnow).Butu canchangey thetwossesthatdon't havetheunderscore, andthisis whatwewillbe doing.237 +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"]].) 99 99 239 + 240 + 241 +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. 242 + 243 + 244 + 100 100 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: 101 101 102 102 {{code}} 103 - 104 104 public String fullName() { 105 105 return this.firstName() + " " + this.lastName(); 106 106 } ... ... @@ -110,16 +110,17 @@ 110 110 Nothing fancy here. Now open **BlogEntry.java** and add the following method: 111 111 112 112 {{code}} 113 - 114 -@Override 257 + @Override 115 115 public void awakeFromInsertion(EOEditingContext editingContext) { 116 - super.awakeFromInsertion(editingContext); 117 - this.setCreationDate(new NSTimestamp()); 259 + super.awakeFromInsertion(editingContext); 260 + NSTimestamp now = new NSTimestamp(); 261 + setCreationDate(now); 262 + setLastModified(now); 118 118 } 119 119 120 120 {{/code}} 121 121 122 -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 th atvalue.267 +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. 123 123 124 124 Now, let's use migrations to actually create the database. 125 125 ... ... @@ -138,7 +138,6 @@ 138 138 Remove the pound char in front of those two properties: 139 139 140 140 {{code}} 141 - 142 142 #er.migration.migrateAtStartup=true 143 143 #er.migration.createTablesIfNecessary=true 144 144 ... ... @@ -147,16 +147,14 @@ 147 147 After removing the pound char, the two properties should look like this: 148 148 149 149 {{code}} 150 - 151 151 er.migration.migrateAtStartup=true 152 152 er.migration.createTablesIfNecessary=true 153 153 154 154 {{/code}} 155 155 156 -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: 299 +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: 157 157 158 158 {{code}} 159 - 160 160 BlogRest[62990] INFO er.extensions.migration.ERXMigrator - Upgrading BlogModel to version 0 with migration 'your.app.model.migrations.BlogModel0@4743bf3d' 161 161 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) 162 162 BlogRest[62990] INFO er.extensions.jdbc.ERXJDBCUtilities - Executing ALTER TABLE Author ADD PRIMARY KEY (id) ... ... @@ -167,7 +167,7 @@ 167 167 168 168 {{/code}} 169 169 170 -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. 312 +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. 171 171 172 172 = Creating REST controllers and routes = 173 173 ... ... @@ -204,15 +204,14 @@ 204 204 * **indexAction**: to list all (or a sublist) of the objects. 205 205 206 206 {{info}} 207 -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. 349 +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 208 {{/info}} 209 209 210 -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) 352 +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 211 212 212 Add this method in **BlogEntryController**: 213 213 214 214 {{code}} 215 - 216 216 protected ERXKeyFilter filter() { 217 217 ERXKeyFilter personFilter = ERXKeyFilter.filterWithAttributes(); 218 218 personFilter.setAnonymousUpdateEnabled(true); ... ... @@ -229,7 +229,6 @@ 229 229 Now, let's implement the **createAction** method: 230 230 231 231 {{code}} 232 - 233 233 public WOActionResults createAction() throws Throwable { 234 234 BlogEntry entry = create(filter()); 235 235 editingContext().saveChanges(); ... ... @@ -243,7 +243,6 @@ 243 243 Last step in the controller: implementing the **indexAction** method. Again, the code is simple: 244 244 245 245 {{code}} 246 - 247 247 public WOActionResults indexAction() throws Throwable { 248 248 NSArray<BlogEntry> entries = BlogEntry.fetchAllBlogEntries(editingContext()); 249 249 return response(entries, filter()); ... ... @@ -260,7 +260,6 @@ 260 260 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: 261 261 262 262 {{code}} 263 - 264 264 ERXRouteRequestHandler restRequestHandler = new ERXRouteRequestHandler(); 265 265 restRequestHandler.addDefaultRoutes(BlogEntry.ENTITY_NAME); 266 266 ERXRouteRequestHandler.register(restRequestHandler); ... ... @@ -270,13 +270,13 @@ 270 270 271 271 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 272 273 -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_]]//411 +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://youripsomeport||shape="rect"]] 274 274 275 275 == Adding posts and authors with curl == 276 276 277 277 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. 278 278 279 -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: 417 +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 280 281 281 {{code}} 282 282 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 ... ... @@ -285,7 +285,6 @@ 285 285 The response should look this: 286 286 287 287 {{code}} 288 - 289 289 HTTP/1.0 201 Apple WebObjects 290 290 Content-Length: 249 291 291 x-webobjects-loadaverage: 0 ... ... @@ -298,7 +298,6 @@ 298 298 To get a list of blog entries: 299 299 300 300 {{code}} 301 - 302 302 curl -X GET http://192.168.0.102:52406/cgi-bin/WebObjects/BlogRest.woa/ra/blogEntries.json 303 303 304 304 {{/code}} ... ... @@ -310,7 +310,6 @@ 310 310 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: 311 311 312 312 {{code}} 313 - 314 314 @Override 315 315 protected boolean isAutomaticHtmlRoutingEnabled() { 316 316 return true; ... ... @@ -318,12 +318,11 @@ 318 318 319 319 {{/code}} 320 320 321 -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**. 456 +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**. 322 322 323 323 The next step to get it to work is to make **BlogEntryIndexPage** to implement the **er.rest.routes.IERXRouteComponent** interface. 324 324 325 325 {{code}} 326 - 327 327 import er.rest.routes.IERXRouteComponent; 328 328 329 329 public class BlogEntryIndexPage extends WOComponent implements IERXRouteComponent { ... ... @@ -333,7 +333,6 @@ 333 333 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: 334 334 335 335 {{code}} 336 - 337 337 public NSArray<BlogEntry> entries() { 338 338 EOEditingContext ec = ERXEC.newEditingContext(); 339 339 return BlogEntry.fetchAllBlogEntries(ec, BlogEntry.CREATION_DATE.descs()); ... ... @@ -344,7 +344,6 @@ 344 344 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**: 345 345 346 346 {{code}} 347 - 348 348 private BlogEntry entryItem; 349 349 350 350 public BlogEntry entryItem() { ... ... @@ -360,7 +360,6 @@ 360 360 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: 361 361 362 362 {{code}} 363 - 364 364 <wo:loop list="$entries" item="$entryItem"> 365 365 <p><wo:str value="$entryItem.title" /></p> 366 366 <p><wo:str value="$entryItem.author.fullName" /></p> ... ... @@ -370,14 +370,13 @@ 370 370 371 371 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. 372 372 373 -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 504 +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! 374 374 375 375 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**. 376 376 377 -Open **BlogEntryShowPage.java** and make sure the class implements **er.rest.routes.IERXRouteComponent**.508 +Open **BlogEntryShowPage.java** and make sure the class implements **er.rest.routes.IERXRouteComponent**. 378 378 379 379 {{code}} 380 - 381 381 import er.rest.routes.IERXRouteComponent; 382 382 383 383 public class BlogEntryShowPage extends WOComponent implements IERXRouteComponent { ... ... @@ -387,7 +387,6 @@ 387 387 We need to add other methods to receive the BlogEntry object from the controller. In **BlogEntryShowPage.java**, add: 388 388 389 389 {{code}} 390 - 391 391 private BlogEntry blogEntry; 392 392 393 393 @ERXRouteParameter ... ... @@ -406,7 +406,6 @@ 406 406 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: 407 407 408 408 {{code}} 409 - 410 410 <h1><wo:str value="$blogEntry.title" /></h1> 411 411 <p><wo:str value="$blogEntry.content" /></p> 412 412 <p>Created on: <wo:str value="$blogEntry.creationDate" dateformat="%Y/%m/%d" /></p> ... ... @@ -417,7 +417,6 @@ 417 417 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: 418 418 419 419 {{code}} 420 - 421 421 <p><wo:str value="$entryItem.title" /></p> 422 422 423 423 {{/code}} ... ... @@ -425,11 +425,10 @@ 425 425 with: 426 426 427 427 {{code}} 428 - 429 429 <p><wo:ERXRouteLink entityName="BlogEntry" record="$entryItem" action="show"><wo:str value="$entryItem.title" /></wo:ERXRouteLink></p> 430 430 431 431 {{/code}} 432 432 433 -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 559 +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! 434 434 435 -The REST part of this tutorial is now complete, [[you can now move to the next part of the tutorial>>Your First Framework]]. 561 +The REST part of this tutorial is now complete, [[you can now move to the next part of the tutorial>>doc:Your First Framework]].