Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
14792 manas 1
/**
2
 * Copyright 2010-present Facebook
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
 
17
package com.facebook.android;
18
 
19
import android.app.AlertDialog.Builder;
20
import android.content.Context;
21
import android.os.Bundle;
22
import com.facebook.internal.Utility;
23
import org.json.JSONException;
24
import org.json.JSONObject;
25
 
26
import java.io.*;
27
import java.net.*;
28
 
29
/**
30
 * Utility class supporting the Facebook Object.
31
 * <p/>
32
 * THIS CLASS SHOULD BE CONSIDERED DEPRECATED.
33
 * <p/>
34
 * All public members of this class are intentionally deprecated.
35
 * New code should instead use
36
 * {@link com.facebook.Request}
37
 * <p/>
38
 * Adding @Deprecated to this class causes warnings in other deprecated classes
39
 * that reference this one.  That is the only reason this entire class is not
40
 * deprecated.
41
 *
42
 * @devDocDeprecated
43
 */
44
public final class Util {
45
 
46
    private final static String UTF8 = "UTF-8";
47
 
48
    /**
49
     * Generate the multi-part post body providing the parameters and boundary
50
     * string
51
     * 
52
     * @param parameters the parameters need to be posted
53
     * @param boundary the random string as boundary
54
     * @return a string of the post body
55
     */
56
    @Deprecated
57
    public static String encodePostBody(Bundle parameters, String boundary) {
58
        if (parameters == null) return "";
59
        StringBuilder sb = new StringBuilder();
60
 
61
        for (String key : parameters.keySet()) {
62
            Object parameter = parameters.get(key);
63
            if (!(parameter instanceof String)) {
64
                continue;
65
            }
66
 
67
            sb.append("Content-Disposition: form-data; name=\"" + key +
68
                    "\"\r\n\r\n" + (String)parameter);
69
            sb.append("\r\n" + "--" + boundary + "\r\n");
70
        }
71
 
72
        return sb.toString();
73
    }
74
 
75
    @Deprecated
76
    public static String encodeUrl(Bundle parameters) {
77
        if (parameters == null) {
78
            return "";
79
        }
80
 
81
        StringBuilder sb = new StringBuilder();
82
        boolean first = true;
83
        for (String key : parameters.keySet()) {
84
            Object parameter = parameters.get(key);
85
            if (!(parameter instanceof String)) {
86
                continue;
87
            }
88
 
89
            if (first) first = false; else sb.append("&");
90
            sb.append(URLEncoder.encode(key) + "=" +
91
                      URLEncoder.encode(parameters.getString(key)));
92
        }
93
        return sb.toString();
94
    }
95
 
96
    @Deprecated
97
    public static Bundle decodeUrl(String s) {
98
        Bundle params = new Bundle();
99
        if (s != null) {
100
            String array[] = s.split("&");
101
            for (String parameter : array) {
102
                String v[] = parameter.split("=");
103
 
104
                try {
105
                    if (v.length == 2) {
106
                        params.putString(URLDecoder.decode(v[0], UTF8),
107
                                         URLDecoder.decode(v[1], UTF8));
108
                    } else if (v.length == 1) {
109
                        params.putString(URLDecoder.decode(v[0], UTF8), "");
110
                    }
111
                } catch (UnsupportedEncodingException e) {
112
                    // shouldn't happen
113
                }
114
            }
115
        }
116
        return params;
117
    }
118
 
119
    /**
120
     * Parse a URL query and fragment parameters into a key-value bundle.
121
     *
122
     * @param url the URL to parse
123
     * @return a dictionary bundle of keys and values
124
     */
125
    @Deprecated
126
    public static Bundle parseUrl(String url) {
127
        // hack to prevent MalformedURLException
128
        url = url.replace("fbconnect", "http");
129
        try {
130
            URL u = new URL(url);
131
            Bundle b = decodeUrl(u.getQuery());
132
            b.putAll(decodeUrl(u.getRef()));
133
            return b;
134
        } catch (MalformedURLException e) {
135
            return new Bundle();
136
        }
137
    }
138
 
139
 
140
    /**
141
     * Connect to an HTTP URL and return the response as a string.
142
     *
143
     * Note that the HTTP method override is used on non-GET requests. (i.e.
144
     * requests are made as "POST" with method specified in the body).
145
     *
146
     * @param url - the resource to open: must be a welformed URL
147
     * @param method - the HTTP method to use ("GET", "POST", etc.)
148
     * @param params - the query parameter for the URL (e.g. access_token=foo)
149
     * @return the URL contents as a String
150
     * @throws MalformedURLException - if the URL format is invalid
151
     * @throws IOException - if a network problem occurs
152
     */
153
    @Deprecated
154
    public static String openUrl(String url, String method, Bundle params)
155
          throws MalformedURLException, IOException {
156
        // random string as boundary for multi-part http post
157
        String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
158
        String endLine = "\r\n";
159
 
160
        OutputStream os;
161
 
162
        if (method.equals("GET")) {
163
            url = url + "?" + encodeUrl(params);
164
        }
165
        Utility.logd("Facebook-Util", method + " URL: " + url);
166
        HttpURLConnection conn =
167
            (HttpURLConnection) new URL(url).openConnection();
168
        conn.setRequestProperty("User-Agent", System.getProperties().
169
                getProperty("http.agent") + " FacebookAndroidSDK");
170
        if (!method.equals("GET")) {
171
            Bundle dataparams = new Bundle();
172
            for (String key : params.keySet()) {
173
                Object parameter = params.get(key);
174
                if (parameter instanceof byte[]) {
175
                    dataparams.putByteArray(key, (byte[])parameter);
176
                }
177
            }
178
 
179
            // use method override
180
            if (!params.containsKey("method")) {
181
                params.putString("method", method);
182
            }
183
 
184
            if (params.containsKey("access_token")) {
185
                String decoded_token =
186
                    URLDecoder.decode(params.getString("access_token"));
187
                params.putString("access_token", decoded_token);
188
            }
189
 
190
            conn.setRequestMethod("POST");
191
            conn.setRequestProperty(
192
                    "Content-Type",
193
                    "multipart/form-data;boundary="+strBoundary);
194
            conn.setDoOutput(true);
195
            conn.setDoInput(true);
196
            conn.setRequestProperty("Connection", "Keep-Alive");
197
            conn.connect();
198
 
199
            os = new BufferedOutputStream(conn.getOutputStream());
200
 
201
            try {
202
                os.write(("--" + strBoundary +endLine).getBytes());
203
                os.write((encodePostBody(params, strBoundary)).getBytes());
204
                os.write((endLine + "--" + strBoundary + endLine).getBytes());
205
 
206
                if (!dataparams.isEmpty()) {
207
 
208
                    for (String key: dataparams.keySet()){
209
                        os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
210
                        os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
211
                        os.write(dataparams.getByteArray(key));
212
                        os.write((endLine + "--" + strBoundary + endLine).getBytes());
213
 
214
                    }
215
                }
216
                os.flush();
217
            } finally {
218
                os.close();
219
            }
220
        }
221
 
222
        String response = "";
223
        try {
224
            response = read(conn.getInputStream());
225
        } catch (FileNotFoundException e) {
226
            // Error Stream contains JSON that we can parse to a FB error
227
            response = read(conn.getErrorStream());
228
        }
229
        return response;
230
    }
231
 
232
    @Deprecated
233
    private static String read(InputStream in) throws IOException {
234
        StringBuilder sb = new StringBuilder();
235
        BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
236
        for (String line = r.readLine(); line != null; line = r.readLine()) {
237
            sb.append(line);
238
        }
239
        in.close();
240
        return sb.toString();
241
    }
242
 
243
    /**
244
     * Parse a server response into a JSON Object. This is a basic
245
     * implementation using org.json.JSONObject representation. More
246
     * sophisticated applications may wish to do their own parsing.
247
     *
248
     * The parsed JSON is checked for a variety of error fields and
249
     * a FacebookException is thrown if an error condition is set,
250
     * populated with the error message and error type or code if
251
     * available.
252
     *
253
     * @param response - string representation of the response
254
     * @return the response as a JSON Object
255
     * @throws JSONException - if the response is not valid JSON
256
     * @throws FacebookError - if an error condition is set
257
     */
258
    @Deprecated
259
    public static JSONObject parseJson(String response)
260
          throws JSONException, FacebookError {
261
        // Edge case: when sending a POST request to /[post_id]/likes
262
        // the return value is 'true' or 'false'. Unfortunately
263
        // these values cause the JSONObject constructor to throw
264
        // an exception.
265
        if (response.equals("false")) {
266
            throw new FacebookError("request failed");
267
        }
268
        if (response.equals("true")) {
269
            response = "{value : true}";
270
        }
271
        JSONObject json = new JSONObject(response);
272
 
273
        // errors set by the server are not consistent
274
        // they depend on the method and endpoint
275
        if (json.has("error")) {
276
            JSONObject error = json.getJSONObject("error");
277
            throw new FacebookError(
278
                    error.getString("message"), error.getString("type"), 0);
279
        }
280
        if (json.has("error_code") && json.has("error_msg")) {
281
            throw new FacebookError(json.getString("error_msg"), "",
282
                    Integer.parseInt(json.getString("error_code")));
283
        }
284
        if (json.has("error_code")) {
285
            throw new FacebookError("request failed", "",
286
                    Integer.parseInt(json.getString("error_code")));
287
        }
288
        if (json.has("error_msg")) {
289
            throw new FacebookError(json.getString("error_msg"));
290
        }
291
        if (json.has("error_reason")) {
292
            throw new FacebookError(json.getString("error_reason"));
293
        }
294
        return json;
295
    }
296
 
297
    /**
298
     * Display a simple alert dialog with the given text and title.
299
     *
300
     * @param context
301
     *          Android context in which the dialog should be displayed
302
     * @param title
303
     *          Alert dialog title
304
     * @param text
305
     *          Alert dialog message
306
     */
307
    @Deprecated
308
    public static void showAlert(Context context, String title, String text) {
309
        Builder alertBuilder = new Builder(context);
310
        alertBuilder.setTitle(title);
311
        alertBuilder.setMessage(text);
312
        alertBuilder.create().show();
313
    }
314
}