Changes for page Your First Rest Project
Last modified by Steve Peery on 2013/09/06 11:02
From version 30.1
edited by Pascal Robert
on 2011/12/27 13:43
on 2011/12/27 13:43
Change comment:
There is no comment for this version
To version 31.1
edited by Pascal Robert
on 2011/12/27 23:07
on 2011/12/27 23:07
Change comment:
There is no comment for this version
Summary
-
Page properties (1 modified, 0 added, 0 removed)
Details
- Page properties
-
- Content
-
... ... @@ -24,7 +24,6 @@ 24 24 | id | integer | primary key 25 25 | title | string(255) | 26 26 | content | string(4000) | 27 -| lastModified | timestamp | 28 28 | creationDate | timestamp | 29 29 | author | integer | relation with Author 30 30 ... ... @@ -35,7 +35,6 @@ 35 35 | firstName | string(50) | 36 36 | lastName | string(50) | 37 37 | email | string(100) | unique 38 -| passwd | string(16) | 39 39 40 40 == Creating the EOModel == 41 41 ... ... @@ -75,7 +75,6 @@ 75 75 76 76 |= Attribute name |= Column |= Prototype 77 77 | content | content | longtext 78 -| lastModified | lastModified | dateTime 79 79 | creationDate | creationDate | dateTime 80 80 81 81 If you did everything well, the list of attributes should look like this: ... ... @@ -88,7 +88,6 @@ 88 88 | firstName | firstName | varchar50 89 89 | lastName | lastName | varchar50 90 90 | email | email | varchar100 91 -| passwd | passwd | varchar16 92 92 93 93 Final list of attributes should look like this: 94 94 ... ... @@ -110,13 +110,27 @@ 110 110 111 111 {{/code}} 112 112 113 -Nothing fancy here. Now ,let'suse migrationstoactuallycreate thedatabase.109 +Nothing fancy here. Now open **BlogEntry.java** and add the following method: 114 114 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 + 115 115 == Using migrations == 116 116 117 -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**. 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**. 118 118 119 -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**. 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**. 120 120 121 121 Type **your.app.model.migrations** as the package and **BlogModel0** as the name of the class. Click **Finish**. 122 122 ... ... @@ -142,14 +142,14 @@ 142 142 143 143 {{/code}} 144 144 145 -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: 146 146 147 147 {{code}} 148 148 149 149 BlogRest[62990] INFO er.extensions.migration.ERXMigrator - Upgrading BlogModel to version 0 with migration 'your.app.model.migrations.BlogModel0@4743bf3d' 150 -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 , passwd VARCHAR(16)NOT NULL)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) 151 151 BlogRest[62990] INFO er.extensions.jdbc.ERXJDBCUtilities - Executing ALTER TABLE Author ADD PRIMARY KEY (id) 152 -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, lastModified TIMESTAMP NOT NULL,title VARCHAR(255) NOT NULL)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) 153 153 BlogRest[62990] INFO er.extensions.jdbc.ERXJDBCUtilities - Executing ALTER TABLE BlogEntry ADD PRIMARY KEY (id) 154 154 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) 155 155 BlogRest[62990] DEBUG NSLog - evaluateExpression: <er.h2.jdbcadaptor.ERH2PlugIn$H2Expression: "UPDATE _dbupdater SET version = ? WHERE modelname = ?" withBindings: 1:0(version), 2:"BlogModel"(modelName)> ... ... @@ -156,6 +156,207 @@ 156 156 157 157 {{/code}} 158 158 159 -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. 160 160 161 161 = 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 +== Creating controllers == 192 + 193 +ERRest needs controllers to act as a broker between working with the objects and the routes. So let's create a controller for BlogEntry. 194 + 195 +Create a Java class named **BlogEntryController**, in the **your.app.rest.controllers** package, that will extend from **er.rest.routes.ERXDefaultRouteController**. Click **Finish**. 196 + 197 +When you extend from **ERXDefaultRouteController**, a bunch of methods are added to the subclass. Let's see what they are for. 198 + 199 +* **updateAction**: to update a specific instance of BlogEntry 200 +* **destroyAction**: to delete a specific instance of BlogEntry 201 +* **showAction**: to get one specific instance of BlogEntry 202 +* **createAction**: to create a new object (a new instance of BlogEntry) 203 +* **indexAction**: to list all (or a sublist) of the objects. 204 + 205 +{{info}} 206 +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. 207 +{{/info}} 208 + 209 +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) 210 + 211 +Add this method in **BlogEntryController**: 212 + 213 +{{code}} 214 + 215 +protected ERXKeyFilter filter() { 216 + ERXKeyFilter personFilter = ERXKeyFilter.filterWithAttributes(); 217 + personFilter.setAnonymousUpdateEnabled(true); 218 + 219 + ERXKeyFilter filter = ERXKeyFilter.filterWithAttributes(); 220 + filter.include(BlogEntry.AUTHOR, personFilter); 221 + filter.setUnknownKeyIgnored(true); 222 + 223 + return filter; 224 + } 225 + 226 +{{/code}} 227 + 228 +Now, let's implement the **creationAction** method: 229 + 230 +{{code}} 231 + 232 +public WOActionResults createAction() throws Throwable { 233 + BlogEntry entry = create(filter()); 234 + editingContext().saveChanges(); 235 + return response(entry, filter()); 236 + } 237 + 238 +{{/code}} 239 + 240 +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? 241 + 242 +Last step in the controller: implementing the **showAction** method. Again, the code is simple: 243 + 244 +{{code}} 245 + 246 +public WOActionResults indexAction() throws Throwable { 247 + NSArray<BlogEntry> entries = BlogEntry.fetchAllBlogEntries(editingContext()); 248 + return response(entries, filter()); 249 + } 250 + 251 +{{/code}} 252 + 253 +That code simply fetch all blog entries and return them in the response. 254 + 255 +We can now go to the next step: adding the routes. 256 + 257 +== Adding the routes == 258 + 259 +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: 260 + 261 +{{code}} 262 + 263 +ERXRouteRequestHandler restRequestHandler = new ERXRouteRequestHandler(); 264 + restRequestHandler.addDefaultRoutes(BlogEntry.ENTITY_NAME); 265 + ERXRouteRequestHandler.register(restRequestHandler); 266 + setDefaultRequestHandler(restRequestHandler); 267 + 268 +{{/code}} 269 + 270 +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. 271 + 272 +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_]]// 273 + 274 +== Adding posts and authors with curl == 275 + 276 +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. 277 + 278 +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: 279 + 280 +{{code}} 281 +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 282 +{{/code}} 283 + 284 +The response should look this: 285 + 286 +{{code}} 287 + 288 +HTTP/1.0 201 Apple WebObjects 289 +Content-Length: 249 290 +x-webobjects-loadaverage: 0 291 +Content-Type: application/json 292 + 293 +{"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"}} 294 + 295 +{{/code}} 296 + 297 +To get a list of blog entries: 298 + 299 +{{code}} 300 + 301 +curl -X GET http://192.168.0.102:52406/cgi-bin/WebObjects/BlogRest.woa/ra/blogEntries.json 302 + 303 +{{/code}} 304 + 305 +You can stop the application and proceed to the next step. 306 + 307 +== Adding HTML views for blog posts == 308 + 309 +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: 310 + 311 +{{code}} 312 + 313 + @Override 314 + protected boolean isAutomaticHtmlRoutingEnabled() { 315 + return true; 316 + } 317 + 318 +{{/code}} 319 + 320 +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**. 321 + 322 +The next step to get it to work is to make **BlogEntryIndexPage** to implements the **er.rest.routes.IERXRouteComponent** interface. 323 + 324 +{{code}} 325 + 326 +import er.rest.routes.IERXRouteComponent; 327 + 328 +public class BlogEntryIndexPage extends WOComponent implements IERXRouteComponent { 329 + 330 +{{/code}} 331 + 332 +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: 333 + 334 +{{code}} 335 + 336 + public NSArray<BlogEntry> entries() { 337 + EOEditingContext ec = ERXEC.newEditingContext(); 338 + return BlogEntry.fetchAllBlogEntries(ec, BlogEntry.CREATION_DATE.descs()); 339 + } 340 + 341 +{{/code}} 342 + 343 +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**: 344 + 345 +{{code}} 346 + 347 + private BlogEntry entryItem; 348 + 349 + public BlogEntry entryItem() { 350 + return entryItem; 351 + } 352 + 353 + public void setEntryItem(BlogEntry entryItem) { 354 + this.entryItem = entryItem; 355 + } 356 + 357 +{{/code}} 358 + 359 +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: 360 + 361 +{{code}} 362 + 363 + <wo:loop list="$entries" item="$entryItem"> 364 + <p><wo:str value="$entryItem.title" /></p> 365 + <p><wo:str value="$entryItem.author.fullName" /></p> 366 + </wo:loop> 367 + 368 +{{/code}} 369 + 370 +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. 371 + 372 +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!//