2 * Copyright (C) 2008 ZXing authors
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.google.zxing.client.android;
19 import android.app.Activity;
20 import android.content.Intent;
21 import android.content.res.Configuration;
22 import android.os.Bundle;
23 import android.os.Handler;
24 import android.os.Message;
25 import android.util.Log;
26 import android.view.KeyEvent;
27 import android.view.LayoutInflater;
28 import android.view.View;
29 import android.webkit.CookieManager;
30 import android.webkit.CookieSyncManager;
31 import android.widget.Button;
32 import android.widget.EditText;
33 import android.widget.ListView;
34 import android.widget.TextView;
35 import org.apache.http.Header;
36 import org.apache.http.HttpEntity;
37 import org.apache.http.HttpResponse;
38 import org.apache.http.client.methods.HttpGet;
39 import org.apache.http.client.methods.HttpHead;
40 import org.apache.http.client.methods.HttpUriRequest;
41 import org.json.JSONArray;
42 import org.json.JSONException;
43 import org.json.JSONObject;
45 import java.io.ByteArrayOutputStream;
46 import java.io.IOException;
48 import java.util.ArrayList;
49 import java.util.List;
52 * Uses Google Book Search to find a word or phrase in the requested book.
54 * @author dswitkin@google.com (Daniel Switkin)
56 public final class SearchBookContentsActivity extends Activity {
57 private static final String TAG = "SearchBookContents";
58 private static final String USER_AGENT = "ZXing (Android)";
60 private NetworkThread networkThread;
62 private EditText queryTextView;
63 private Button queryButton;
64 private ListView resultListView;
65 private TextView headerView;
67 public final Handler handler = new Handler() {
69 public void handleMessage(Message message) {
70 switch (message.what) {
71 case R.id.search_book_contents_succeeded:
72 handleSearchResults((JSONObject) message.obj);
75 case R.id.search_book_contents_failed:
77 headerView.setText(R.string.msg_sbc_failed);
83 private final Button.OnClickListener buttonListener = new Button.OnClickListener() {
84 public void onClick(View view) {
89 private final View.OnKeyListener keyListener = new View.OnKeyListener() {
90 public boolean onKey(View view, int keyCode, KeyEvent event) {
91 if (keyCode == KeyEvent.KEYCODE_ENTER) {
100 public void onCreate(Bundle icicle) {
101 super.onCreate(icicle);
103 // Make sure that expired cookies are removed on launch.
104 CookieSyncManager.createInstance(this);
105 CookieManager.getInstance().removeExpiredCookie();
107 Intent intent = getIntent();
108 if (intent == null || (!intent.getAction().equals(Intents.SearchBookContents.ACTION))) {
113 isbn = intent.getStringExtra(Intents.SearchBookContents.ISBN);
114 setTitle(getString(R.string.sbc_name) + ": ISBN " + isbn);
116 setContentView(R.layout.search_book_contents);
117 queryTextView = (EditText) findViewById(R.id.query_text_view);
119 String initialQuery = intent.getStringExtra(Intents.SearchBookContents.QUERY);
120 if (initialQuery != null && initialQuery.length() > 0) {
121 // Populate the search box but don't trigger the search
122 queryTextView.setText(initialQuery);
124 queryTextView.setOnKeyListener(keyListener);
126 queryButton = (Button) findViewById(R.id.query_button);
127 queryButton.setOnClickListener(buttonListener);
129 resultListView = (ListView) findViewById(R.id.result_list_view);
130 LayoutInflater factory = LayoutInflater.from(this);
131 headerView = (TextView) factory.inflate(R.layout.search_book_contents_header,
132 resultListView, false);
133 resultListView.addHeaderView(headerView);
137 protected void onResume() {
139 queryTextView.selectAll();
143 public void onConfigurationChanged(Configuration config) {
144 // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
145 super.onConfigurationChanged(config);
148 private void resetForNewQuery() {
149 networkThread = null;
150 queryTextView.setEnabled(true);
151 queryTextView.selectAll();
152 queryButton.setEnabled(true);
155 private void launchSearch() {
156 if (networkThread == null) {
157 String query = queryTextView.getText().toString();
158 if (query != null && query.length() > 0) {
159 networkThread = new NetworkThread(isbn, query, handler);
160 networkThread.start();
161 headerView.setText(R.string.msg_sbc_searching_book);
162 resultListView.setAdapter(null);
163 queryTextView.setEnabled(false);
164 queryButton.setEnabled(false);
169 // Currently there is no way to distinguish between a query which had no results and a book
170 // which is not searchable - both return zero results.
171 private void handleSearchResults(JSONObject json) {
173 int count = json.getInt("number_of_results");
174 headerView.setText("Found " + (count == 1 ? "1 result" : count + " results"));
176 JSONArray results = json.getJSONArray("search_results");
177 SearchBookContentsResult.setQuery(queryTextView.getText().toString());
178 List<SearchBookContentsResult> items = new ArrayList<SearchBookContentsResult>(count);
179 for (int x = 0; x < count; x++) {
180 items.add(parseResult(results.getJSONObject(x)));
182 resultListView.setAdapter(new SearchBookContentsAdapter(this, items));
184 String searchable = json.optString("searchable");
185 if ("false".equals(searchable)) {
186 headerView.setText(R.string.msg_sbc_book_not_searchable);
188 resultListView.setAdapter(null);
190 } catch (JSONException e) {
191 Log.e(TAG, e.toString());
192 resultListView.setAdapter(null);
193 headerView.setText(R.string.msg_sbc_failed);
197 // Available fields: page_number, page_id, page_url, snippet_text
198 private SearchBookContentsResult parseResult(JSONObject json) {
200 String pageNumber = json.getString("page_number");
201 if (pageNumber.length() > 0) {
202 pageNumber = getString(R.string.msg_sbc_page) + ' ' + pageNumber;
204 // This can happen for text on the jacket, and possibly other reasons.
205 pageNumber = getString(R.string.msg_sbc_unknown_page);
208 // Remove all HTML tags and encoded characters. Ideally the server would do this.
209 String snippet = json.optString("snippet_text");
210 boolean valid = true;
211 if (snippet.length() > 0) {
212 snippet = snippet.replaceAll("\\<.*?\\>", "");
213 snippet = snippet.replaceAll("<", "<");
214 snippet = snippet.replaceAll(">", ">");
215 snippet = snippet.replaceAll("'", "'");
216 snippet = snippet.replaceAll(""", "\"");
218 snippet = '(' + getString(R.string.msg_sbc_snippet_unavailable) + ')';
221 return new SearchBookContentsResult(pageNumber, snippet, valid);
222 } catch (JSONException e) {
223 // Never seen in the wild, just being complete.
224 return new SearchBookContentsResult(getString(R.string.msg_sbc_no_page_returned), "", false);
228 private static final class NetworkThread extends Thread {
229 private final String isbn;
230 private final String query;
231 private final Handler handler;
233 NetworkThread(String isbn, String query, Handler handler) {
236 this.handler = handler;
241 AndroidHttpClient client = null;
243 // These return a JSON result which describes if and where the query was found. This API may
244 // break or disappear at any time in the future. Since this is an API call rather than a
245 // website, we don't use LocaleManager to change the TLD.
246 URI uri = new URI("http", null, "www.google.com", -1, "/books", "vid=isbn" + isbn +
247 "&jscmd=SearchWithinVolume2&q=" + query, null);
248 HttpUriRequest get = new HttpGet(uri);
249 get.setHeader("cookie", getCookie(uri.toString()));
250 client = AndroidHttpClient.newInstance(USER_AGENT);
251 HttpResponse response = client.execute(get);
252 if (response.getStatusLine().getStatusCode() == 200) {
253 HttpEntity entity = response.getEntity();
254 ByteArrayOutputStream jsonHolder = new ByteArrayOutputStream();
255 entity.writeTo(jsonHolder);
257 JSONObject json = new JSONObject(jsonHolder.toString(getEncoding(entity)));
260 Message message = Message.obtain(handler, R.id.search_book_contents_succeeded);
262 message.sendToTarget();
264 Log.e(TAG, "HTTP returned " + response.getStatusLine().getStatusCode() + " for " + uri);
265 Message message = Message.obtain(handler, R.id.search_book_contents_failed);
266 message.sendToTarget();
268 } catch (Exception e) {
269 Log.e(TAG, e.toString());
270 Message message = Message.obtain(handler, R.id.search_book_contents_failed);
271 message.sendToTarget();
273 if (client != null) {
279 // Book Search requires a cookie to work, which we store persistently. If the cookie does
280 // not exist, this could be the first search or it has expired. Either way, do a quick HEAD
281 // request to fetch it, save it via the CookieSyncManager to flash, then return it.
282 private String getCookie(String url) {
283 String cookie = CookieManager.getInstance().getCookie(url);
284 if (cookie == null || cookie.length() == 0) {
285 Log.v(TAG, "Book Search cookie was missing or expired");
286 HttpUriRequest head = new HttpHead(url);
287 AndroidHttpClient client = AndroidHttpClient.newInstance(USER_AGENT);
289 HttpResponse response = client.execute(head);
290 if (response.getStatusLine().getStatusCode() == 200) {
291 Header[] cookies = response.getHeaders("set-cookie");
292 for (Header theCookie : cookies) {
293 CookieManager.getInstance().setCookie(url, theCookie.getValue());
295 CookieSyncManager.getInstance().sync();
296 cookie = CookieManager.getInstance().getCookie(url);
298 } catch (IOException e) {
299 Log.e(TAG, e.toString());
306 private static String getEncoding(HttpEntity entity) {
307 // FIXME: The server is returning ISO-8859-1 but the content is actually windows-1252.
308 // Once Jeff fixes the HTTP response, remove this hardcoded value and go back to getting
309 // the encoding dynamically.
310 return "windows-1252";
311 // HeaderElement[] elements = entity.getContentType().getElements();
312 // if (elements != null && elements.length > 0) {
313 // String encoding = elements[0].getParameterByName("charset").getValue();
314 // if (encoding != null && encoding.length() > 0) {