1 package ro
.ieval
.fonbot
;
3 import static ro
.ieval
.fonbot
.Utils
.toNonNull
;
5 import java
.io
.InputStream
;
7 import org
.json
.JSONArray
;
8 import org
.json
.JSONObject
;
10 import android
.content
.Context
;
11 import android
.os
.Handler
;
12 import android
.os
.Looper
;
13 import android
.util
.Log
;
15 import ro
.ieval
.fonbot
.Address
.Protocol
;
16 import ro
.ieval
.fonbot
.HttpCallExecutableRunnable
.ResultCallback
;
19 * Copyright © 2013 Marius Gavrilescu
21 * This file is part of FonBot.
23 * FonBot is free software: you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation, either version 3 of the License, or
26 * (at your option) any later version.
28 * FonBot is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
33 * You should have received a copy of the GNU General Public License
34 * along with FonBot. If not, see <http://www.gnu.org/licenses/>.
38 * ResultCallback implementation that polls the server for pending commands.
40 * @author Marius Gavrilescu <marius@ieval.ro>
42 final class PollResultCallback
implements ResultCallback
{
43 /** Context instance */
44 private final Context context
;
47 * Construct a <code>PollResultCallback</code> with a Context.
49 * @param context Context instance
51 public PollResultCallback(final Context context
) {
56 public void onResult(int responseCode
, String responseMessage
,
57 InputStream inputStream
) {
61 final Handler handler
=new Handler(Looper
.getMainLooper());
64 final JSONArray array
;
66 final byte[] buf
=new byte[2048*1024];
67 final int length
=inputStream
.read(buf
);
68 array
=new JSONArray(new String(buf
, 0, length
));
71 for(int i
=0;i
<array
.length();i
++){
72 final JSONObject object
=array
.getJSONObject(i
);
74 final JSONArray jsonargs
=object
.getJSONArray("args");
75 final String command
=object
.getString("command");
76 final Address replyTo
=new Address(toNonNull(Protocol
.HTTP
), object
.getString("replyto"));//NOPMD address depends on command
77 final String
[] args
=new String
[jsonargs
.length()];
78 for(int j
=0;j
<args
.length
;j
++)
79 args
[j
]=jsonargs
.getString(j
);
81 Log
.d(getClass().getName(), "Poll got command "+command
+" with "+((args
.length
==0)?
"no args":"args "+Utils
.join(
82 " ",toNonNull(args
))));
84 handler
.post(new Runnable() {
100 public void onError(final String error
) {
101 Log
.e("PollResultCallback", "onError: "+error
);