examples: annotate examples
[nit.git] / lib / app / examples / http_request_example.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Example for the `app::http_request` main service `AsyncHttpRequest`
16 module http_request_example is
17 example
18 app_name "app.nit HTTP"
19 app_namespace "org.nitlanguage.http_example"
20 android_api_target 15
21 end
22
23 import app::ui
24 import app::http_request
25 import android::aware # for android_api_target
26
27 # Simple asynchronous HTTP request to http://example.com/ displaying feedback to the window
28 class MyHttpRequest
29 super AsyncHttpRequest
30
31 # Back reference to the window to show feedback to the user
32 var win: HttpRequestClientWindow
33
34 # ---
35 # Config the request
36
37 redef fun uri do return "http://example.com/"
38 redef fun deserialize_json do return false
39
40 # ---
41 # Customize callbacks
42
43 redef fun before
44 do
45 win.label_response.text = "Sending request..."
46
47 # Disable button to prevent double requests
48 win.button_request.enabled = false
49 end
50
51 redef fun on_load(data, status)
52 do win.label_response.text = "Received response code {status} with {data.as(Text).byte_length} bytes"
53
54 redef fun on_fail(error)
55 do win.label_response.text = "Connection error: {error}"
56
57 redef fun after do win.button_request.enabled = true
58 end
59
60 # Simple window with a label and a button
61 class HttpRequestClientWindow
62 super Window
63
64 # Root layout
65 var layout = new ListLayout(parent=self)
66
67 # Button to send request
68 var button_request = new Button(parent=layout, text="Press to send HTTP request")
69
70 # Label displaying feedback to user
71 var label_response = new Label(parent=layout, text="No response yet.")
72
73 init do button_request.observers.add self
74
75 redef fun on_event(event)
76 do
77 if event isa ButtonPressEvent and event.sender == button_request then
78 # Prepare and send request
79 var request = new MyHttpRequest(self)
80 request.start
81 end
82 end
83 end
84
85 redef fun root_window do return new HttpRequestClientWindow