KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > gwt > sample > json > client > JSON


1 /*
2  * Copyright 2006 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy of
6  * the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations under
14  * the License.
15  */

16 package com.google.gwt.sample.json.client;
17
18 import com.google.gwt.json.client.JSONArray;
19 import com.google.gwt.json.client.JSONException;
20 import com.google.gwt.json.client.JSONObject;
21 import com.google.gwt.json.client.JSONParser;
22 import com.google.gwt.json.client.JSONString;
23 import com.google.gwt.json.client.JSONValue;
24 import com.google.gwt.user.client.HTTPRequest;
25 import com.google.gwt.user.client.ResponseTextHandler;
26 import com.google.gwt.user.client.Window;
27 import com.google.gwt.user.client.ui.Button;
28 import com.google.gwt.user.client.ui.ClickListener;
29 import com.google.gwt.user.client.ui.RootPanel;
30 import com.google.gwt.user.client.ui.Tree;
31 import com.google.gwt.user.client.ui.TreeItem;
32 import com.google.gwt.user.client.ui.Widget;
33
34 import java.util.Iterator JavaDoc;
35 import java.util.Set JavaDoc;
36
37 /**
38  * Class that acts as a client to a JSON service. Currently, this client just
39  * requests a text which contains a JSON encoding of a search result set from
40  * yahoo. We use a text file to demonstrate how the pieces work without tripping
41  * on cross-site scripting issues.
42  *
43  * If you would like to make this a more dynamic example, you can associate a
44  * servlet with this example and simply have it hit the yahoo service and return
45  * the results.
46  */

47 public class JSON {
48   /**
49    * Class for handling the response text associated with a request for a JSON
50    * object.
51    *
52    */

53   private class JSONResponseTextHandler implements ResponseTextHandler {
54     public void onCompletion(String JavaDoc responseText) {
55       try {
56         JSONValue jsonValue = JSONParser.parse(responseText);
57         displayJSONObject(jsonValue);
58       } catch (JSONException e) {
59         displayError(responseText);
60       }
61       searchButton.setText(SEARCH_BUTTON_DEFAULT_TEXT);
62     }
63   }
64
65   /*
66    * Class for handling the fetch button's click event.
67    */

68   private class SearchButtonClickListener implements ClickListener {
69     public void onClick(Widget sender) {
70       jsonTree.setVisible(false);
71       doFetchURL();
72     }
73   }
74
75   /*
76    * Default URL to use to fetch JSON objects. Note that the contents of this
77    * JSON result were as a result of requesting the following URL:
78    *
79    * http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=potato&results=2&output=json
80    *
81    */

82   private static final String JavaDoc DEFAULT_SEARCH_URL = "search-results.js";
83
84   /*
85    * Text displayed on the fetch button when we are in a default state.
86    */

87   private static final String JavaDoc SEARCH_BUTTON_DEFAULT_TEXT = "Search";
88
89   /*
90    * Text displayed on the fetch button when we are waiting for a JSON reply.
91    */

92   private static final String JavaDoc SEARCH_BUTTON_WAITING_TEXT = "Waiting for JSON Response...";
93
94   private Tree jsonTree = new Tree();
95
96   private Button searchButton = new Button();
97
98   /**
99    * Entry point for this simple application. Currently, we build the
100    * application's form and wait for events.
101    */

102   public void onModuleLoad() {
103     initializeMainForm();
104   }
105
106   /*
107    * Add the object presented by the JSONValue as a children to the requested
108    * TreeItem.
109    */

110   private void addChildren(TreeItem treeItem, JSONValue jsonValue) {
111     JSONArray jsonArray;
112     JSONObject jsonObject;
113     JSONString jsonString;
114
115     if ((jsonArray = jsonValue.isArray()) != null) {
116       for (int i = 0; i < jsonArray.size(); ++i) {
117         TreeItem child = treeItem.addItem(getChildText("["
118             + Integer.toString(i) + "]"));
119         addChildren(child, jsonArray.get(i));
120       }
121     } else if ((jsonObject = jsonValue.isObject()) != null) {
122       Set JavaDoc keys = jsonObject.keySet();
123       for (Iterator JavaDoc iter = keys.iterator(); iter.hasNext();) {
124         String JavaDoc key = (String JavaDoc) iter.next();
125         TreeItem child = treeItem.addItem(getChildText(key));
126         addChildren(child, jsonObject.get(key));
127       }
128     } else if ((jsonString = jsonValue.isString()) != null) {
129       // Use stringValue instead of toString() because we don't want escaping
130
treeItem.addItem(jsonString.stringValue());
131     } else {
132       // JSONBoolean, JSONNumber, and JSONNull work well with toString().
133
treeItem.addItem(getChildText(jsonValue.toString()));
134     }
135   }
136
137   private void displayError(String JavaDoc responseText) {
138     jsonTree.removeItems();
139     jsonTree.setVisible(true);
140     TreeItem treeItem = jsonTree.addItem("Failed to parse JSON response");
141     treeItem.addItem(responseText);
142     treeItem.setStyleName("JSON-JSONResponseObject");
143     treeItem.setState(true);
144   }
145
146   /*
147    * Update the treeview of a JSON object.
148    */

149   private void displayJSONObject(JSONValue jsonValue) {
150     jsonTree.removeItems();
151     jsonTree.setVisible(true);
152     TreeItem treeItem = jsonTree.addItem("JSON Response");
153     addChildren(treeItem, jsonValue);
154     treeItem.setStyleName("JSON-JSONResponseObject");
155     treeItem.setState(true);
156   }
157
158   /*
159    * Fetch the requested URL.
160    */

161   private void doFetchURL() {
162     searchButton.setText(SEARCH_BUTTON_WAITING_TEXT);
163     if (!HTTPRequest.asyncGet(DEFAULT_SEARCH_URL, new JSONResponseTextHandler())) {
164       // Reset the caption.
165
//
166
searchButton.setText(SEARCH_BUTTON_DEFAULT_TEXT);
167     }
168   }
169
170   /*
171    * Causes the text of child elements to wrap.
172    */

173   private String JavaDoc getChildText(String JavaDoc text) {
174     return "<span style='white-space:normal'>" + text + "</span>";
175   }
176
177   /**
178    * Initialize the main form's layout and content.
179    */

180   private void initializeMainForm() {
181     searchButton.setStyleName("JSON-SearchButton");
182     searchButton.setText(SEARCH_BUTTON_DEFAULT_TEXT);
183     searchButton.addClickListener(new SearchButtonClickListener());
184
185     // Avoids showing an "empty" cell
186
jsonTree.setVisible(false);
187
188     // Find out where the host page wants the button.
189
//
190
RootPanel searchButtonSlot = RootPanel.get("search");
191     if (searchButtonSlot == null) {
192       Window.alert("Please define a container element whose id is 'search'");
193       return;
194     }
195
196     // Find out where the host page wants the tree view.
197
//
198
RootPanel treeViewSlot = RootPanel.get("tree");
199     if (treeViewSlot == null) {
200       Window.alert("Please define a container element whose id is 'tree'");
201       return;
202     }
203
204     // Add both widgets.
205
//
206
searchButtonSlot.add(searchButton);
207     treeViewSlot.add(jsonTree);
208   }
209 }
210
Popular Tags