FrameworkListener.cpp revision 168415b822cae1f8b54ef09c41c11a9b97b87f40
1/*
2 * Copyright (C) 2008 The Android Open Source Project
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#include <errno.h>
17
18#define LOG_TAG "FrameworkListener"
19
20#include <cutils/log.h>
21
22#include <sysutils/FrameworkListener.h>
23#include <sysutils/FrameworkCommand.h>
24
25FrameworkListener::FrameworkListener(const char *socketName) :
26                            SocketListener(socketName, true) {
27    mCommands = new FrameworkCommandCollection();
28}
29
30bool FrameworkListener::onDataAvailable(int socket) {
31    char buffer[101];
32    int len;
33
34    if ((len = read(socket, buffer, sizeof(buffer) -1)) < 0) {
35        LOGE("read() failed (%s)", strerror(errno));
36        return errno;
37    } else if (!len) {
38        LOGW("Lost connection to client");
39        return false;
40    }
41
42    int start = 0;
43    int i;
44
45    buffer[len] = '\0';
46
47    for (i = 0; i < len; i++) {
48        if (buffer[i] == '\0') {
49            dispatchCommand(buffer + start);
50            start = i + 1;
51        }
52    }
53    return true;
54}
55
56void FrameworkListener::registerCmd(FrameworkCommand *cmd) {
57    mCommands->push_back(cmd);
58}
59
60void FrameworkListener::dispatchCommand(char *cmd) {
61    FrameworkCommandCollection::iterator i;
62
63    for (i = mCommands->begin(); i != mCommands->end(); ++i) {
64        FrameworkCommand *c = *i;
65
66        if (!strncmp(cmd, c->getCommand(), strlen(c->getCommand()))) {
67            if (c->runCommand(cmd)) {
68                LOGW("Handler '%s' error (%s)", c->getCommand(), strerror(errno));
69            }
70            return;
71        }
72    }
73
74    LOGE("No cmd handlers defined for '%s'", cmd);
75}
76
77