PageRenderTime 21ms CodeModel.GetById 2ms app.highlight 15ms RepoModel.GetById 1ms app.codeStats 0ms

/hazelcast/src/main/java/com/hazelcast/nio/ascii/SocketTextReader.java

https://bitbucket.org/gabral6_gmailcom/hazelcast
Java | 181 lines | 147 code | 18 blank | 16 comment | 29 complexity | 8cdf3cc19aaa2debfb7224ba3213c369 MD5 | raw file
  1/*
  2 * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
  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
 17package com.hazelcast.nio.ascii;
 18
 19import com.hazelcast.impl.ascii.CommandParser;
 20import com.hazelcast.impl.ascii.TextCommand;
 21import com.hazelcast.impl.ascii.TextCommandConstants;
 22import com.hazelcast.impl.ascii.TextCommandService;
 23import com.hazelcast.impl.ascii.memcache.*;
 24import com.hazelcast.impl.ascii.rest.HttpCommand;
 25import com.hazelcast.impl.ascii.rest.HttpDeleteCommandParser;
 26import com.hazelcast.impl.ascii.rest.HttpGetCommandParser;
 27import com.hazelcast.impl.ascii.rest.HttpPostCommandParser;
 28import com.hazelcast.logging.ILogger;
 29import com.hazelcast.nio.Connection;
 30import com.hazelcast.nio.IOService;
 31import com.hazelcast.nio.SocketReader;
 32
 33import java.nio.ByteBuffer;
 34import java.util.HashMap;
 35import java.util.Map;
 36import java.util.logging.Level;
 37
 38import static com.hazelcast.impl.ascii.TextCommandConstants.TextCommandType.*;
 39
 40public class SocketTextReader implements TextCommandConstants, SocketReader {
 41
 42    private final static Map<String, CommandParser> mapCommandParsers = new HashMap<String, CommandParser>();
 43
 44    static {
 45        mapCommandParsers.put("get", new GetCommandParser());
 46        mapCommandParsers.put("gets", new GetCommandParser());
 47        mapCommandParsers.put("set", new SetCommandParser(SET));
 48        mapCommandParsers.put("add", new SetCommandParser(ADD));
 49        mapCommandParsers.put("replace", new SetCommandParser(REPLACE));
 50        mapCommandParsers.put("append", new SetCommandParser(APPEND));
 51        mapCommandParsers.put("prepend", new SetCommandParser(PREPEND));
 52        mapCommandParsers.put("delete", new DeleteCommandParser());
 53        mapCommandParsers.put("quit", new SimpleCommandParser(QUIT));
 54        mapCommandParsers.put("stats", new SimpleCommandParser(STATS));
 55        mapCommandParsers.put("GET", new HttpGetCommandParser());
 56        mapCommandParsers.put("POST", new HttpPostCommandParser());
 57        mapCommandParsers.put("PUT", new HttpPostCommandParser());
 58        mapCommandParsers.put("DELETE", new HttpDeleteCommandParser());
 59    }
 60
 61    ByteBuffer commandLine = ByteBuffer.allocate(500);
 62    boolean commandLineRead = false;
 63    TextCommand command = null;
 64    private final TextCommandService textCommandService;
 65    private final SocketTextWriter socketTextWriter;
 66    private final Connection connection;
 67    private final boolean restEnabled;
 68    private final boolean memcacheEnabled;
 69    boolean connectionTypeSet = false;
 70    long requestIdGen;
 71    private final ILogger logger;
 72
 73    public SocketTextReader(Connection connection) {
 74        IOService ioService = connection.getConnectionManager().getIOHandler();
 75        this.textCommandService = ioService.getTextCommandService();
 76        this.socketTextWriter = (SocketTextWriter) connection.getWriteHandler().getSocketWriter();
 77        this.connection = connection;
 78        this.memcacheEnabled = ioService.isMemcacheEnabled();
 79        this.restEnabled = ioService.isRestEnabled();
 80        this.logger = ioService.getLogger(this.getClass().getName());
 81    }
 82
 83    public void sendResponse(TextCommand command) {
 84        socketTextWriter.enqueue(command);
 85    }
 86
 87    public void read(ByteBuffer inBuffer) {
 88        while (inBuffer.hasRemaining()) {
 89            doRead(inBuffer);
 90        }
 91    }
 92
 93    private void doRead(ByteBuffer bb) {
 94        while (!commandLineRead && bb.hasRemaining()) {
 95            byte b = bb.get();
 96            char c = (char) b;
 97            if (c == '\n') {
 98                commandLineRead = true;
 99            } else if (c != '\r') {
100                commandLine.put(b);
101            }
102        }
103        if (commandLineRead) {
104            if (command == null) {
105                processCmd(toStringAndClear(commandLine));
106            }
107            if (command != null) {
108                boolean complete = command.doRead(bb);
109                if (complete) {
110                    publishRequest(command);
111                    reset();
112                }
113            } else {
114                reset();
115            }
116        }
117    }
118
119    void reset() {
120        command = null;
121        commandLine.clear();
122        commandLineRead = false;
123    }
124
125    public static String toStringAndClear(ByteBuffer bb) {
126        if (bb == null) return "";
127        String result = null;
128        if (bb.position() == 0) {
129            result = "";
130        } else {
131            result = new String(bb.array(), 0, bb.position());
132        }
133        bb.clear();
134        return result;
135    }
136
137    public void publishRequest(TextCommand command) {
138//        System.out.println("publishing " + command);
139        if (!connectionTypeSet) {
140            if (command instanceof HttpCommand) {
141                if (!restEnabled) {
142                    connection.close();
143                }
144                connection.setType(Connection.Type.REST_CLIENT);
145            } else {
146                if (!memcacheEnabled) {
147                    connection.close();
148                }
149                connection.setType(Connection.Type.MEMCACHE_CLIENT);
150            }
151            connectionTypeSet = true;
152        }
153        long requestId = (command.shouldReply()) ? requestIdGen++ : -1;
154        command.init(this, requestId);
155        textCommandService.processRequest(command);
156    }
157
158    void processCmd(String cmd) {
159        try {
160            int space = cmd.indexOf(' ');
161            String operation = (space == -1) ? cmd : cmd.substring(0, space);
162            CommandParser commandParser = mapCommandParsers.get(operation);
163            if (commandParser != null) {
164                command = commandParser.parser(this, cmd, space);
165            } else {
166                command = new ErrorCommand(UNKNOWN);
167            }
168        } catch (Throwable t) {
169            logger.log(Level.FINEST, t.getMessage(), t);
170            command = new ErrorCommand(ERROR_CLIENT, "Invalid command : " + cmd);
171        }
172    }
173
174    public SocketTextWriter getSocketTextWriter() {
175        return socketTextWriter;
176    }
177
178    public void closeConnection() {
179        connection.close();
180    }
181}