34c5d8d8260265be43ee1e6edee0460d1accf95b
[fonbot.git] / src / ro / ieval / fonbot / HttpCallExecutableRunnable.java
1 package ro.ieval.fonbot;
2
3 import static ro.ieval.fonbot.R.string.*;
4 import static ro.ieval.fonbot.Utils.toNonNull;
5
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.net.HttpURLConnection;
9 import java.net.URL;
10 import java.util.Collection;
11
12 import org.eclipse.jdt.annotation.Nullable;
13
14 import android.content.Context;
15 import android.preference.PreferenceManager;
16 import android.util.Base64;
17 import android.util.Log;
18
19 import com.google.android.gcm.GCMRegistrar;
20
21 /*
22 * Copyright © 2013 Marius Gavrilescu
23 *
24 * This file is part of FonBot.
25 *
26 * FonBot is free software: you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation, either version 3 of the License, or
29 * (at your option) any later version.
30 *
31 * FonBot is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
35 *
36 * You should have received a copy of the GNU General Public License
37 * along with FonBot. If not, see <http://www.gnu.org/licenses/>.
38 */
39
40 /**
41 * ExecutableRunnable that makes a HTTP call to the server and hands the response to a callback
42 *
43 * @author Marius Gavrilescu <marius@ieval.ro>
44 */
45 public final class HttpCallExecutableRunnable extends ExecutableRunnable{
46 /**
47 * Callback which is run after a HTTP call.
48 *
49 * @author Marius Gavrilescu
50 */
51 public static interface ResultCallback{
52 /**
53 * Callback invoked if the HTTP call is successful.
54 *
55 * @param responseCode HTTP response code
56 * @param responseMessage HTTP response message
57 * @param inputStream HTTP content InputStream
58 */
59 public void onResult(final int responseCode, final String responseMessage, final InputStream inputStream);
60 /**
61 * Callback invoked if the HTTP call is unsuccessful.
62 *
63 * @param error localized error message
64 */
65 public void onError(final String error);
66 }
67
68 /**
69 * List of extra request headers.
70 */
71 private final Collection<Header> headers;
72 /**
73 * Context instance used by this class
74 */
75 private final Context context;
76 /**
77 * Data to send to the server
78 */
79 private final byte[] data;
80 /**
81 * Server URL path
82 */
83 private final String path;
84 /**
85 * Callback to run after the request returns
86 */
87 private final ResultCallback callback;
88
89 /**
90 * Constructs a SendHttpMessageAsyncTask which sends a binary message.
91 *
92 * @param path URL path
93 * @param headers the extra headers
94 * @param context the context instance
95 * @param resultCallback {@link ResultCallback} instance
96 * @param data the message to send
97 */
98 public HttpCallExecutableRunnable(final String path, final @Nullable Collection<Header> headers, final Context context, final @Nullable ResultCallback resultCallback, final byte[] data){//NOPMD array is supposed to be immutable.
99 this.path=path;
100 this.headers=headers;
101 this.context=context;
102 this.callback=resultCallback;
103 this.data=data;
104 }
105
106 /**
107 * Constructs a SendHttpMessageAsyncTask which sends a text message.
108 *
109 * @param path URL path
110 * @param headers the extra headers
111 * @param context the context instance
112 * @param resultCallback {@link ResultCallback} instance
113 * @param message message to send
114 */
115 public HttpCallExecutableRunnable(final String path, final @Nullable Collection<Header> headers, final Context context, final @Nullable ResultCallback resultCallback, final String... message){
116 this.path=path;
117 this.headers=headers;
118 this.context=context;
119 this.callback=resultCallback;
120 if(message.length == 0)
121 this.data=null;//NOPMD final field
122 else
123 this.data=Utils.join(" ", message).getBytes();
124 }
125
126 @Override
127 public void run() {
128 try {
129 final URL url=Utils.getServerURL(toNonNull(context),toNonNull(path));
130 final HttpURLConnection conn=(HttpURLConnection) url.openConnection();
131 if(data!=null){
132 conn.setDoOutput(true);
133 conn.setFixedLengthStreamingMode(data.length);
134 }
135 conn.setRequestProperty("X-ID", GCMRegistrar.getRegistrationId(context));
136 final String user=PreferenceManager.getDefaultSharedPreferences(context).getString("username", null);
137 final String password=PreferenceManager.getDefaultSharedPreferences(context).getString("password", null);
138 if(user == null || password == null){
139 if(callback!=null)
140 callback.onError(toNonNull(context.getString(user_or_password_not_set)));
141 return;
142 }
143
144 conn.setRequestProperty("Authorization", "Basic "+Base64.encodeToString(
145 (user+':'+password).getBytes(), Base64.NO_WRAP));
146 if(headers != null)
147 for (final Header header : headers)
148 conn.setRequestProperty(header.name, header.value);
149 conn.connect();
150 if(data!=null){
151 final OutputStream stream=conn.getOutputStream();
152 stream.write(data);
153 stream.close();
154 }
155 Log.d(getClass().getName(),"HTTP Response: "+conn.getResponseCode()+" "+conn.getResponseMessage());
156 final String message=conn.getResponseMessage();
157 if(message==null && callback != null)
158 callback.onError(toNonNull(context.getString(no_response_returned_from_server)));
159 else if(message != null && callback != null)
160 callback.onResult(conn.getResponseCode(), Utils.parseHttpMessage(message),
161 toNonNull(conn.getInputStream()));
162 conn.disconnect();
163 } catch (Exception e) {
164 e.printStackTrace();
165 if(callback != null)
166 callback.onError(toNonNull(context.getString(connection_error)));
167 }
168 }
169 }
This page took 0.024896 seconds and 3 git commands to generate.