Wednesday, October 30, 2013

REST API

I recently read a new book RESTful Web APIs by Leonard Richardson and Mike Amundsen. A key notes about REST API I presented in this post.

REST

Representational State Transfer (REST) is not a protocol, a file format, or a development framework. REST is an architectural style. Another definition says that REST is a set of design constraints. REST was initially described in the context of HTTP, but it is not limited to that protocol. RESTful architectures may be based on other Application Layer protocols if they already provide a rich and uniform vocabulary for applications based on the transfer of meaningful representational state.

The REST architectural style describes the following six constraints applied to the architecture:

Client–server
Servers are not concerned with the user interface or user state, so that servers can be simpler and more scalable. Servers and clients may also be replaced and developed independently, as long as the interface between them is not altered.

Stateless
Each request from any client contains all of the information necessary to service the request, and session state is held in the client.

Cacheable
As on the World Wide Web, clients can cache responses. Well-managed caching partially or completely eliminates some client–server interactions, further improving scalability and performance.

Layered system
A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches. They may also enforce security policies.

Uniform interface
The uniform interface between clients and servers, simplifies and decouples the architecture, which enables each part to evolve independently.

Code on demand - optional
Servers can temporarily extend or customize the functionality of a client by the transfer of executable code. Examples of this may include compiled components such as Java applets and client-side scripts such as JavaScript.

Resources and representation

Individual resources are identified in requests, for example using URIs in web-based REST systems. The resources themselves are conceptually separate from the representations that are returned to the client. For example, the server does not send its database, but rather, some HTML, XML or JSON that represents some database records.

Although a resource can be anything at all, a client can’t do whatever it wants to a resource. There are rules. In a RESTful system, clients and servers interact only by sending each other messages that follow a predefined protocol.

The HTTP standard defines eight different kinds of messages.

GET
The client sends a GET request to ask for a representation of a resource, identified by a URL. The GET is defined as a safe HTTP method.  It’s just a request for information.

The most common response code to a GET request is 200 (OK). Redirect codes like 301 (Moved Permanently) are also common.

DELETE
The client sends a DELETE request when it wants a resource to go away. If a DELETE request succeeds, the possible status codes are 204 (No Content), 200 (OK); and 202 (Accepted).

If a client tries to GET a resource that has been DELETEd, the server will return an error response code, usually 404 (Not Found) or 410 (Gone).

DELETE is not a safe method. Once you delete a resource, it’s gone. The resource state has permanently changed. You can send another DELETE request, and you might get a 404 error, but the resource state is exactly as it was after the first request. The resource is still gone. That’s idempotence.

POST
Sending a POST request to a resource creates a new resource. When a client sends a POST request, it sends a representation of the resource it wants to create in the request’s entity-body. The most common response code to a POST request is 201 (Created). The Location header lets the client know the URL to this new resource. Another common response code is 202 (Accepted), which means that the server intends to create a new resource based on the given representation, but hasn’t actually created it yet.

The POST method is neither safe nor idempotent. Every POST create a new resource.

PUT
A PUT request is a request to modify resource state. The client takes the representation it got from a GET request, modifies it, and sends it back as the payload of a PUT request. If the server decides to accept a PUT request, the server changes the resource state to match what the client says in the representation, and usually sends either 200 (OK) or 204 (No Content).

PUT is idempotent, just like DELETE. If you send the same PUT request 10 times, the result is the same as if you’d only sent it once.

HEAD
HEAD is a safe method, just like GET. The server is supposed to treat a HEAD request exactly the same as a GET request, but it’s not supposed to send a an entity-body—only the HTTP status code and the headers.

Using HEAD instead of GET may not save any time (the server still has to generate all the appropriate HTTP headers), but it will definitely save bandwidth.

OPTIONS
OPTIONS is a primitive discovery mechanism for HTTP. The response to an OPTIONS request contains the HTTP Allow header, which lays out which HTTP methods the resource supports.

200 OK
Allow: GET PUT DELETE HEAD OPTIONS

PATCH
Representations can get really big. “Modify the representation and PUT it back” is a simple rule, but if you just want to change one little bit of resource state, it can be pretty wasteful. The PUT rule can also lead to unintentional conflicts with other users who are modifying the same document. It would be nice if you could just send the server the parts of the document you want to change.

The PATCH method allows for this. Instead of PUTting a full representation, you can create a special “diff ” representation and send it to the server as the payload of a PATCH request.

The best response codes for a successful PATCH are the same as for PUT and DELETE: 200 (OK) if the server wants to send data (such as an updated representation of the resource) along with its response, and 204 (No Content) if the server just wants to indicate success.

PATCH is neither safe nor idempotent.

Remember that PATCH is not defined in the HTTP specification. It’s an extension designed specifically for web APIs, and it’s relatively recent (RFC 5789 was published in 2010). This means that tool support for PATCH, and for the diff
documents it uses, is not as good as the support for PUT.

LINK and UNLINK
LINK and UNLINK manage the hypermedia links between resources. These methods are defined in an Internet-Draft, and until that draft is approved as an RFC, tool support for them will be even worse than for PATCH.

LINK and UNLINK are idempotent, but not safe.

Monday, September 30, 2013

Add HTML5 video to old Internet Explorer - Google Chrome Frame

Google Chrome Frame is plugin for Internet Explorer 6, 7, 8, 9. The plugin replaces the slow JavaScript Engine of IE and adds WebKit kernel. It adds HTML5 video, canvas, WebGL, CSS3 and other feature to old IE browsers. In this article I show how to use Google Chrome Frame.

Rendering

You can enable Google Chrome Frame to render a page by adding an HTML metatag or using an HTTP header.


For HTML metatag add to head of your web page:
<meta http-equiv="X-UA-Compatible" content="chrome=1">

For HTTP header let send your web server header:
X-UA-Compatible: chrome=1

Prompting

For detect Google Chrome Frame and prompt users to install the plug-in you can use server-side sniffing or the CFInstall.js script. The big advantage is that users can install Google Chrome Frame without having administrative privileges on their machines. For more options see source code or developer documentation.






In June 2013 Google announced they would retire Chrome Frame, and will cease support and updates for the product in January 2014.

Video from Google IO




Tuesday, August 13, 2013

Converting video for web with FFmpeg

The plight of the HTML5 video format is bad and it looks like that will soon not change.


Formats overview:
  • WebM ( video codec: VP8, audio codec: Vorbis )
  • OGG ( video codec: Theora, audio codec: Vorbis )
  • MP4 ( video codec: H.264, audio codec: ACC/ MP3 )
  • Flash video ( video codec: H.264, audio codec: ACC/ MP3 )




MediaInfo
MediaInfo is a tool for reading video files metadata. Using it is very simple:


FFmpeg
FFmpeg is tool for converting audio and video files. It uses libavcodec library. Converting video files with FFmpeg to required formats ist simple:


WebM
ffmpeg -i INPUT_FILE -acodec libvorbis -vcodec libvpx -b 400k OUTPUT_FILE.webm


OGG
ffmpeg -i INPUT_FILE -acodec libvorbis -vcodec libtheora -b 400k OUTPUT_FILE.ogg


MP4
ffmpeg -i INPUT_FILE -acodec libfaac -vcodec libx264 -b 400k OUTPUT_FILE.mp4


Parameters:
  • -acodec: audio codec, or -c:a in new release of FFmpeg
  • -vcodec: video codec, or -c:v in new release of FFmpeg


There are a lots of others interesting parameters.


libfaac
For the libfaac codec you need the FFmpeg compiled with --enable-libfaac. For more details read FFmpeg Wiki. Or you can use libvo_aacenc codec:
-acodec libvo_aacenc


Bash script for converting video
For painless conversions you can use a prepared bash script.


Use:
  • ./web_video_converter.sh MY_VIDEO_FILE.avi
  • ./web_video_converter.sh FOLDER_WITH_VIDEOS

Monday, July 1, 2013

HTML5 game - decision tree

Most game entity, that you create for your HTML5 games needs our own intelligence. It has to decide what to do next. For example: walks, attacks, speaks, … In this post I show you how to make decision with decision tree.


Consider the following scenario:





This type of the presentation is easy to represent in the form of a tree:


It is better to convert each condition on a separate object. Then you can check the condition and return either a decision or another decision object.




Finally, you need to create the tree and let it make the decision:





Reference:








Thursday, June 6, 2013

Google Closure - custom events in examples

Google Closure Library provides powerful handling system for managing events and listeners across browsers. Closure makes it possible to manage user-defined events too. With Google Closure Library you do not need to create your own Events system.


There are responsible classes in goog.event package. Headstones of google.event package are:
  • goog.events.listen()
  • goog.events.unlistenByKey(key);
  • goog.events.EventTarget
  • goog.events.Event
  • goog.events.EventHandler


Basic use
For basic use you make do with the function goog.events.listen(). Remove listener before destroying object is very important. You do not want memory leaks in your application. But hold reference to key it is inconvenient (read more). You could also be interested in the method goog.events.listenOnce().


Create custom event

The base event object is a goog.events.Event. If you build user defined events you will probably need to extend this class.

Create event target
An EventTarget is an object that can dispatch events. The most common example of an EventTarget is a DOM element but you can define your own EventTarget by inherit from class goog.events.EventTarget. You could also be interested that goog.events.EventTarget extends goog.Disposable. The object responsible for release object reference such as DOM nodes, COM object and register listeners. Subclass of goog.events.EventTarget can register listeners and dispatch events.

Manage listeners
Subclass of goog.events.EventHandler is useful in the release of listeners. After calling method dispose() it release all references to listeners. You can combine it with class goog.Disposable as mentioned bellow.

Monday, May 27, 2013

Create custom tileset in Gimp

There are lots of nice tilesets on Internet for game developers. Some resources you see at the end of this blogpost. For your game you probably need tiles from more tilesets or just some tiles from a large tileset. In this tutorial I show you how to prepare your own tileset for game in excellent image editor Gimp.

For my game I need only trees and some ground from nice 32x32 tileset that I found on opengameart.org.

Prepare grid

1. Open the source tileset: File > Open
2. Set grid spacing: Image > Configure Grid...

3. Show grid:
View > Show Grid
View > Snap to Grid
View > Snap to Canvas Edges

New tileset

1. Create new Image: File > New
Set size. For width I set 5 * 32, For height I set 3 * 32.

2. Set the same grid property as above.

Copy tiles from source to destination

1. Copy tile to new tileset: Use Rectangle Select Tool and select tile or tiles from source tileset. (I used Zoom Tool too).

2. Copy tile: Edit > Copy
3. Paste tile: Switch to the prepared new image. Edit > Paste
4. Place the tile to grid. Use Move Tool. Because you have previously set Snap to Grid, the tile will be glued to the grid.

5. Merge layer. After copying the tiles there was a new layer - Pasted layer. Click on the anchor icon to merge layers into one. (See image above.)
6. Add more tiles with the same procedure.

7. Save your new tileset as PNG.
Gimp 2.6: File > Save As
Gimp 2.8: File > Export

Tileset resource