Upgrade to the latest server protocol.
[fonbot.git] / src / ro / ieval / fonbot / PollServerAsyncTask.java
CommitLineData
8dfb76c9
MG
1package ro.ieval.fonbot;
2
3import static ro.ieval.fonbot.Utils.toNonNull;
4
5import java.io.IOException;
6import java.net.HttpURLConnection;
7import java.net.MalformedURLException;
8import java.net.URL;
9import java.util.ArrayList;
10import java.util.List;
11
12import org.eclipse.jdt.annotation.Nullable;
13import org.json.JSONArray;
14import org.json.JSONException;
15import org.json.JSONObject;
16
17import ro.ieval.fonbot.Address.Protocol;
a97d31fb 18import android.content.Context;
8dfb76c9 19import android.os.AsyncTask;
d13f1533
MG
20import android.preference.PreferenceManager;
21import android.util.Base64;
8dfb76c9
MG
22import android.util.Log;
23
24/*
25 * Copyright © 2013 Marius Gavrilescu
26 *
27 * This file is part of FonBot.
28 *
29 * FonBot is free software: you can redistribute it and/or modify
30 * it under the terms of the GNU General Public License as published by
31 * the Free Software Foundation, either version 3 of the License, or
32 * (at your option) any later version.
33 *
34 * FonBot is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 * GNU General Public License for more details.
38 *
39 * You should have received a copy of the GNU General Public License
40 * along with FonBot. If not, see <http://www.gnu.org/licenses/>.
41 */
42
43/**
44 * AsyncTask that polls the server for pending commands and executes any commands found.
45 *
46 * @author Marius Gavrilescu <marius@ieval.ro>
47 */
48public final class PollServerAsyncTask extends AsyncTask<Void, Void, List<PollServerAsyncTask.Command>> {
49 /**
50 * POJO that represents a command in a basic form: a command name, a list of arguments and a reply address, all of them being strings
51 *
52 * @author Marius Gavrilescu <marius@ieval.ro>
53 */
54 final class Command{
55 /**
56 * The command name
57 */
58 final String command;//NOPMD no confusion here
59 /**
60 * The list of command arguments
61 */
62 final String[] args;
63 /**
64 * The reply address, excluding the protocol
65 */
66 final String replyto;
67
68 /**
69 * Construct a Command from its three parts
70 *
71 * @param command the command name
72 * @param args the command arguments
73 * @param replyto the reply address
74 */
75 Command(final String command, final String[] args, final String replyto) {//NOPMD array is immutable
76 this.command=command;
77 this.args=args;
78 this.replyto=replyto;
79 }
80 }
81
a97d31fb
MG
82 /** Context instance */
83 private final Context context;
84
85 /**
86 * Constructs a PollServerAsyncTask.
87 *
88 * @param context Context instance
89 */
90 public PollServerAsyncTask(final Context context) {
91 this.context=context;
92 }
93
8dfb76c9
MG
94 @Override
95 protected List<Command> doInBackground(final @Nullable Void... params) {
96 Log.d(getClass().getName(), "Polling server");
97 final List<Command> commands=new ArrayList<Command>(10);
98 try {
a97d31fb 99 final URL url=Utils.getServerURL(toNonNull(context),"/get");
8dfb76c9
MG
100 final HttpURLConnection conn=(HttpURLConnection) url.openConnection();
101 conn.setRequestProperty("X-ID", FonBotApplication.instance.regID);
d13f1533
MG
102 final String user=PreferenceManager.getDefaultSharedPreferences(context).getString("username", null);
103 final String password=PreferenceManager.getDefaultSharedPreferences(context).getString("password", null);
104 if(user == null || password == null)
105 return commands;
106
107 conn.setRequestProperty("Authorization", "Basic "+Base64.encodeToString(
108 (user+':'+password).getBytes(), Base64.NO_WRAP));
8dfb76c9
MG
109 conn.connect();
110 final byte[] buf=new byte[4096*1024];
111 Log.d(getClass().getName(), "Server poll got response code "+conn.getResponseCode()+" and message "+conn.getResponseMessage());
112 if(conn.getResponseCode()!=200)
113 return commands;
114 conn.getInputStream().read(buf);
115 final JSONArray array=new JSONArray(new String(buf));
116 final List<String> list=new ArrayList<String>();
117 for(int i=0;i<array.length();i++){
118 final JSONObject object=array.getJSONObject(i);
119
120 for(int j=0;object.has("arg"+j);j++)
121 list.add(object.getString("arg"+j));
122
123 commands.add(new Command(//NOPMD command changes for each JSON object
124 toNonNull(object.getString("command")),
125 toNonNull(list.toArray(new String[list.size()])),
126 toNonNull(object.getString("replyto"))));
127 list.clear();
128 }
129 } catch (MalformedURLException e) {
130 e.printStackTrace();
131 } catch (IOException e) {
132 e.printStackTrace();
133 } catch (JSONException e) {
134 e.printStackTrace();
135 }
136 if(commands==null)
137 throw new AssertionError("commands is null in PollServerAsyncTask#doInBackground");//silence Eclipse bug
138 return commands;
139 }
140
141 @Override
142 protected void onPostExecute(final @Nullable List<Command> commands) {
143 if(commands==null)
144 return;
145 for (Command command : commands) {
146 Log.d(getClass().getName(), "Poll got command "+command.command+" with "+((command.args.length==0)?"no args":"args "+Utils.join(
147 " ",toNonNull(command.args))));
148 Utils.processCommand(
149 toNonNull(FonBotApplication.instance),
150 toNonNull(command.command),
151 toNonNull(command.args),
152 new Address(toNonNull(Protocol.HTTP), command.replyto));//NOPMD address depends on command
153 }
154 }
155}
This page took 0.019558 seconds and 4 git commands to generate.