GoogleSuggestClient.java revision e29d52aa72c96c3147fa91d83aeb8dafc6d1f578
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
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
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,
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.
15 */
16
17package com.android.quicksearchbox.google;
18
19import com.android.quicksearchbox.R;
20import com.android.quicksearchbox.Source;
21import com.android.quicksearchbox.SourceResult;
22import com.android.quicksearchbox.SuggestionCursor;
23
24import org.apache.http.HttpResponse;
25import org.apache.http.client.HttpClient;
26import org.apache.http.client.methods.HttpGet;
27import org.apache.http.impl.client.DefaultHttpClient;
28import org.apache.http.params.HttpParams;
29import org.apache.http.params.HttpProtocolParams;
30import org.apache.http.util.EntityUtils;
31import org.json.JSONArray;
32import org.json.JSONException;
33
34import android.content.ComponentName;
35import android.content.Context;
36import android.net.ConnectivityManager;
37import android.net.NetworkInfo;
38import android.os.Handler;
39import android.text.TextUtils;
40import android.util.Log;
41
42import java.io.IOException;
43import java.io.UnsupportedEncodingException;
44import java.net.URLEncoder;
45import java.util.Locale;
46
47/**
48 * Use network-based Google Suggests to provide search suggestions.
49 */
50public class GoogleSuggestClient extends AbstractGoogleSource {
51
52    private static final boolean DBG = false;
53    private static final String LOG_TAG = "GoogleSearch";
54
55    private static final String USER_AGENT = "Android/1.0";
56    private String mSuggestUri;
57    private static final int HTTP_TIMEOUT_MS = 1000;
58
59    // TODO: this should be defined somewhere
60    private static final String HTTP_TIMEOUT = "http.connection-manager.timeout";
61
62    private final HttpClient mHttpClient;
63
64    public GoogleSuggestClient(Context context, Handler uiThread) {
65        super(context, uiThread);
66        mHttpClient = new DefaultHttpClient();
67        HttpParams params = mHttpClient.getParams();
68        HttpProtocolParams.setUserAgent(params, USER_AGENT);
69        params.setLongParameter(HTTP_TIMEOUT, HTTP_TIMEOUT_MS);
70
71        // NOTE:  Do not look up the resource here;  Localization changes may not have completed
72        // yet (e.g. we may still be reading the SIM card).
73        mSuggestUri = null;
74    }
75
76    @Override
77    public ComponentName getIntentComponent() {
78        return new ComponentName(getContext(), GoogleSearch.class);
79    }
80
81    @Override
82    public SourceResult queryInternal(String query) {
83        return query(query);
84    }
85
86    @Override
87    public SourceResult queryExternal(String query) {
88        return query(query);
89    }
90
91    /**
92     * Queries for a given search term and returns a cursor containing
93     * suggestions ordered by best match.
94     */
95    private SourceResult query(String query) {
96        if (TextUtils.isEmpty(query)) {
97            return null;
98        }
99        if (!isNetworkConnected()) {
100            Log.i(LOG_TAG, "Not connected to network.");
101            return null;
102        }
103        try {
104            query = URLEncoder.encode(query, "UTF-8");
105            if (mSuggestUri == null) {
106                Locale l = Locale.getDefault();
107                String language = GoogleSearch.getLanguage(l);
108                mSuggestUri = getContext().getResources().getString(R.string.google_suggest_base,
109                                                                    language)
110                        + "json=true&q=";
111            }
112
113            String suggestUri = mSuggestUri + query;
114            if (DBG) Log.d(LOG_TAG, "Sending request: " + suggestUri);
115            HttpGet method = new HttpGet(suggestUri);
116            HttpResponse response = mHttpClient.execute(method);
117            if (response.getStatusLine().getStatusCode() == 200) {
118
119                /* Goto http://www.google.com/complete/search?json=true&q=foo
120                 * to see what the data format looks like. It's basically a json
121                 * array containing 4 other arrays. We only care about the middle
122                 * 2 which contain the suggestions and their popularity.
123                 */
124                JSONArray results = new JSONArray(EntityUtils.toString(response.getEntity()));
125                JSONArray suggestions = results.getJSONArray(1);
126                JSONArray popularity = results.getJSONArray(2);
127                if (DBG) Log.d(LOG_TAG, "Got " + suggestions.length() + " results");
128                return new GoogleSuggestCursor(this, query, suggestions, popularity);
129            } else {
130                if (DBG) Log.d(LOG_TAG, "Request failed " + response.getStatusLine());
131            }
132        } catch (UnsupportedEncodingException e) {
133            Log.w(LOG_TAG, "Error", e);
134        } catch (IOException e) {
135            Log.w(LOG_TAG, "Error", e);
136        } catch (JSONException e) {
137            Log.w(LOG_TAG, "Error", e);
138        }
139        return null;
140    }
141
142    @Override
143    public SuggestionCursor refreshShortcut(String shortcutId, String oldExtraData) {
144        return null;
145    }
146
147    private boolean isNetworkConnected() {
148        NetworkInfo networkInfo = getActiveNetworkInfo();
149        return networkInfo != null && networkInfo.isConnected();
150    }
151
152    private NetworkInfo getActiveNetworkInfo() {
153        ConnectivityManager connectivity =
154                (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
155        if (connectivity == null) {
156            return null;
157        }
158        return connectivity.getActiveNetworkInfo();
159    }
160
161    private static class GoogleSuggestCursor extends AbstractGoogleSourceResult {
162
163        /* Contains the actual suggestions */
164        private final JSONArray mSuggestions;
165
166        /* This contains the popularity of each suggestion
167         * i.e. 165,000 results. It's not related to sorting.
168         */
169        private final JSONArray mPopularity;
170
171        public GoogleSuggestCursor(Source source, String userQuery,
172                JSONArray suggestions, JSONArray popularity) {
173            super(source, userQuery);
174            mSuggestions = suggestions;
175            mPopularity = popularity;
176        }
177
178        @Override
179        public int getCount() {
180            return mSuggestions.length();
181        }
182
183        @Override
184        public String getSuggestionQuery() {
185            try {
186                return mSuggestions.getString(getPosition());
187            } catch (JSONException e) {
188                Log.w(LOG_TAG, "Error parsing response: " + e);
189                return null;
190            }
191        }
192
193        @Override
194        public String getSuggestionText2() {
195            try {
196                return mPopularity.getString(getPosition());
197            } catch (JSONException e) {
198                Log.w(LOG_TAG, "Error parsing response: " + e);
199                return null;
200            }
201        }
202    }
203}
204