mobile/android/base/sync/CommandProcessor.java

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 /* This Source Code Form is subject to the terms of the Mozilla Public
michael@0 2 * License, v. 2.0. If a copy of the MPL was not distributed with this
michael@0 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0 4
michael@0 5 package org.mozilla.gecko.sync;
michael@0 6
michael@0 7 import java.util.ArrayList;
michael@0 8 import java.util.List;
michael@0 9 import java.util.Map;
michael@0 10 import java.util.concurrent.ConcurrentHashMap;
michael@0 11 import java.util.concurrent.atomic.AtomicInteger;
michael@0 12
michael@0 13 import org.json.simple.JSONArray;
michael@0 14 import org.json.simple.JSONObject;
michael@0 15 import org.mozilla.gecko.BrowserLocaleManager;
michael@0 16 import org.mozilla.gecko.R;
michael@0 17 import org.mozilla.gecko.background.common.log.Logger;
michael@0 18 import org.mozilla.gecko.sync.repositories.NullCursorException;
michael@0 19 import org.mozilla.gecko.sync.repositories.android.ClientsDatabaseAccessor;
michael@0 20 import org.mozilla.gecko.sync.repositories.domain.ClientRecord;
michael@0 21
michael@0 22 import android.app.Notification;
michael@0 23 import android.app.NotificationManager;
michael@0 24 import android.app.PendingIntent;
michael@0 25 import android.content.Context;
michael@0 26 import android.content.Intent;
michael@0 27 import android.net.Uri;
michael@0 28
michael@0 29 /**
michael@0 30 * Process commands received from Sync clients.
michael@0 31 * <p>
michael@0 32 * We need a command processor at two different times:
michael@0 33 * <ol>
michael@0 34 * <li>We execute commands during the "clients" engine stage of a Sync. Each
michael@0 35 * command takes a <code>GlobalSession</code> instance as a parameter.</li>
michael@0 36 * <li>We queue commands to be executed or propagated to other Sync clients
michael@0 37 * during an activity completely unrelated to a sync (such as
michael@0 38 * <code>SendTabActivity</code>.)</li>
michael@0 39 * </ol>
michael@0 40 * To provide a processor for both these time frames, we maintain a static
michael@0 41 * long-lived singleton.
michael@0 42 */
michael@0 43 public class CommandProcessor {
michael@0 44 private static final String LOG_TAG = "Command";
michael@0 45 private static AtomicInteger currentId = new AtomicInteger();
michael@0 46 protected ConcurrentHashMap<String, CommandRunner> commands = new ConcurrentHashMap<String, CommandRunner>();
michael@0 47
michael@0 48 private final static CommandProcessor processor = new CommandProcessor();
michael@0 49
michael@0 50 /**
michael@0 51 * Get the global singleton command processor.
michael@0 52 *
michael@0 53 * @return the singleton processor.
michael@0 54 */
michael@0 55 public static CommandProcessor getProcessor() {
michael@0 56 return processor;
michael@0 57 }
michael@0 58
michael@0 59 public static class Command {
michael@0 60 public final String commandType;
michael@0 61 public final JSONArray args;
michael@0 62 private List<String> argsList;
michael@0 63
michael@0 64 public Command(String commandType, JSONArray args) {
michael@0 65 this.commandType = commandType;
michael@0 66 this.args = args;
michael@0 67 }
michael@0 68
michael@0 69 /**
michael@0 70 * Get list of arguments as strings. Individual arguments may be null.
michael@0 71 *
michael@0 72 * @return list of strings.
michael@0 73 */
michael@0 74 public synchronized List<String> getArgsList() {
michael@0 75 if (argsList == null) {
michael@0 76 ArrayList<String> argsList = new ArrayList<String>(args.size());
michael@0 77
michael@0 78 for (int i = 0; i < args.size(); i++) {
michael@0 79 final Object arg = args.get(i);
michael@0 80 if (arg == null) {
michael@0 81 argsList.add(null);
michael@0 82 continue;
michael@0 83 }
michael@0 84 argsList.add(arg.toString());
michael@0 85 }
michael@0 86 this.argsList = argsList;
michael@0 87 }
michael@0 88 return this.argsList;
michael@0 89 }
michael@0 90
michael@0 91 @SuppressWarnings("unchecked")
michael@0 92 public JSONObject asJSONObject() {
michael@0 93 JSONObject out = new JSONObject();
michael@0 94 out.put("command", this.commandType);
michael@0 95 out.put("args", this.args);
michael@0 96 return out;
michael@0 97 }
michael@0 98 }
michael@0 99
michael@0 100 /**
michael@0 101 * Register a command.
michael@0 102 * <p>
michael@0 103 * Any existing registration is overwritten.
michael@0 104 *
michael@0 105 * @param commandType
michael@0 106 * the name of the command, i.e., "displayURI".
michael@0 107 * @param command
michael@0 108 * the <code>CommandRunner</code> instance that should handle the
michael@0 109 * command.
michael@0 110 */
michael@0 111 public void registerCommand(String commandType, CommandRunner command) {
michael@0 112 commands.put(commandType, command);
michael@0 113 }
michael@0 114
michael@0 115 /**
michael@0 116 * Process a command in the context of the given global session.
michael@0 117 *
michael@0 118 * @param session
michael@0 119 * the <code>GlobalSession</code> instance currently executing.
michael@0 120 * @param unparsedCommand
michael@0 121 * command as a <code>ExtendedJSONObject</code> instance.
michael@0 122 */
michael@0 123 public void processCommand(final GlobalSession session, ExtendedJSONObject unparsedCommand) {
michael@0 124 Command command = parseCommand(unparsedCommand);
michael@0 125 if (command == null) {
michael@0 126 Logger.debug(LOG_TAG, "Invalid command: " + unparsedCommand + " will not be processed.");
michael@0 127 return;
michael@0 128 }
michael@0 129
michael@0 130 CommandRunner executableCommand = commands.get(command.commandType);
michael@0 131 if (executableCommand == null) {
michael@0 132 Logger.debug(LOG_TAG, "Command \"" + command.commandType + "\" not registered and will not be processed.");
michael@0 133 return;
michael@0 134 }
michael@0 135
michael@0 136 executableCommand.executeCommand(session, command.getArgsList());
michael@0 137 }
michael@0 138
michael@0 139 /**
michael@0 140 * Parse a JSON command into a ParsedCommand object for easier handling.
michael@0 141 *
michael@0 142 * @param unparsedCommand - command as ExtendedJSONObject
michael@0 143 * @return - null if command is invalid, else return ParsedCommand with
michael@0 144 * no null attributes.
michael@0 145 */
michael@0 146 protected static Command parseCommand(ExtendedJSONObject unparsedCommand) {
michael@0 147 String type = (String) unparsedCommand.get("command");
michael@0 148 if (type == null) {
michael@0 149 return null;
michael@0 150 }
michael@0 151
michael@0 152 try {
michael@0 153 JSONArray unparsedArgs = unparsedCommand.getArray("args");
michael@0 154 if (unparsedArgs == null) {
michael@0 155 return null;
michael@0 156 }
michael@0 157
michael@0 158 return new Command(type, unparsedArgs);
michael@0 159 } catch (NonArrayJSONException e) {
michael@0 160 Logger.debug(LOG_TAG, "Unable to parse args array. Invalid command");
michael@0 161 return null;
michael@0 162 }
michael@0 163 }
michael@0 164
michael@0 165 @SuppressWarnings("unchecked")
michael@0 166 public void sendURIToClientForDisplay(String uri, String clientID, String title, String sender, Context context) {
michael@0 167 Logger.info(LOG_TAG, "Sending URI to client " + clientID + ".");
michael@0 168 if (Logger.LOG_PERSONAL_INFORMATION) {
michael@0 169 Logger.pii(LOG_TAG, "URI is " + uri + "; title is '" + title + "'.");
michael@0 170 }
michael@0 171
michael@0 172 final JSONArray args = new JSONArray();
michael@0 173 args.add(uri);
michael@0 174 args.add(sender);
michael@0 175 args.add(title);
michael@0 176
michael@0 177 final Command displayURICommand = new Command("displayURI", args);
michael@0 178 this.sendCommand(clientID, displayURICommand, context);
michael@0 179 }
michael@0 180
michael@0 181 /**
michael@0 182 * Validates and sends a command to a client or all clients.
michael@0 183 *
michael@0 184 * Calling this does not actually sync the command data to the server. If the
michael@0 185 * client already has the command/args pair, it won't receive a duplicate
michael@0 186 * command.
michael@0 187 *
michael@0 188 * @param clientID
michael@0 189 * Client ID to send command to. If null, send to all remote
michael@0 190 * clients.
michael@0 191 * @param command
michael@0 192 * Command to invoke on remote clients
michael@0 193 */
michael@0 194 public void sendCommand(String clientID, Command command, Context context) {
michael@0 195 Logger.debug(LOG_TAG, "In sendCommand.");
michael@0 196
michael@0 197 CommandRunner commandData = commands.get(command.commandType);
michael@0 198
michael@0 199 // Don't send commands that we don't know about.
michael@0 200 if (commandData == null) {
michael@0 201 Logger.error(LOG_TAG, "Unknown command to send: " + command);
michael@0 202 return;
michael@0 203 }
michael@0 204
michael@0 205 // Don't send a command with the wrong number of arguments.
michael@0 206 if (!commandData.argumentsAreValid(command.getArgsList())) {
michael@0 207 Logger.error(LOG_TAG, "Expected " + commandData.argCount + " args for '" +
michael@0 208 command + "', but got " + command.args);
michael@0 209 return;
michael@0 210 }
michael@0 211
michael@0 212 if (clientID != null) {
michael@0 213 this.sendCommandToClient(clientID, command, context);
michael@0 214 return;
michael@0 215 }
michael@0 216
michael@0 217 ClientsDatabaseAccessor db = new ClientsDatabaseAccessor(context);
michael@0 218 try {
michael@0 219 Map<String, ClientRecord> clientMap = db.fetchAllClients();
michael@0 220 for (ClientRecord client : clientMap.values()) {
michael@0 221 this.sendCommandToClient(client.guid, command, context);
michael@0 222 }
michael@0 223 } catch (NullCursorException e) {
michael@0 224 Logger.error(LOG_TAG, "NullCursorException when fetching all GUIDs");
michael@0 225 } finally {
michael@0 226 db.close();
michael@0 227 }
michael@0 228 }
michael@0 229
michael@0 230 protected void sendCommandToClient(String clientID, Command command, Context context) {
michael@0 231 Logger.info(LOG_TAG, "Sending " + command.commandType + " to " + clientID);
michael@0 232
michael@0 233 ClientsDatabaseAccessor db = new ClientsDatabaseAccessor(context);
michael@0 234 try {
michael@0 235 db.store(clientID, command);
michael@0 236 } catch (NullCursorException e) {
michael@0 237 Logger.error(LOG_TAG, "NullCursorException: Unable to send command.");
michael@0 238 } finally {
michael@0 239 db.close();
michael@0 240 }
michael@0 241 }
michael@0 242
michael@0 243 private static volatile boolean didUpdateLocale = false;
michael@0 244
michael@0 245 @SuppressWarnings("deprecation")
michael@0 246 public static void displayURI(final List<String> args, final Context context) {
michael@0 247 // We trust the client sender that these exist.
michael@0 248 final String uri = args.get(0);
michael@0 249 final String clientId = args.get(1);
michael@0 250
michael@0 251 Logger.pii(LOG_TAG, "Received a URI for display: " + uri + " from " + clientId);
michael@0 252
michael@0 253 String title = null;
michael@0 254 if (args.size() == 3) {
michael@0 255 title = args.get(2);
michael@0 256 }
michael@0 257
michael@0 258 // We don't care too much about races, but let's try to avoid
michael@0 259 // unnecessary work.
michael@0 260 if (!didUpdateLocale) {
michael@0 261 BrowserLocaleManager.getInstance().getAndApplyPersistedLocale(context);
michael@0 262 didUpdateLocale = true;
michael@0 263 }
michael@0 264
michael@0 265 final String ns = Context.NOTIFICATION_SERVICE;
michael@0 266 final NotificationManager notificationManager = (NotificationManager) context.getSystemService(ns);
michael@0 267
michael@0 268 // Create a Notification.
michael@0 269 final int icon = R.drawable.icon;
michael@0 270 String notificationTitle = context.getString(R.string.sync_new_tab);
michael@0 271 if (title != null) {
michael@0 272 notificationTitle = notificationTitle.concat(": " + title);
michael@0 273 }
michael@0 274
michael@0 275 final long when = System.currentTimeMillis();
michael@0 276 Notification notification = new Notification(icon, notificationTitle, when);
michael@0 277 notification.flags = Notification.FLAG_AUTO_CANCEL;
michael@0 278
michael@0 279 // Set pending intent associated with the notification.
michael@0 280 Intent notificationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
michael@0 281 PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
michael@0 282 notification.setLatestEventInfo(context, notificationTitle, uri, contentIntent);
michael@0 283
michael@0 284 // Send notification.
michael@0 285 notificationManager.notify(currentId.getAndIncrement(), notification);
michael@0 286 }
michael@0 287 }

mercurial