Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (c) 2014 "Kaazing Corporation," (www.kaazing.com)
   *
   * This file is part of Robot.
   *
   * Robot is free software: you can redistribute it and/or modify
   * it under the terms of the GNU Affero General Public License as
   * published by the Free Software Foundation, either version 3 of the
   * License, or (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU Affero General Public License for more details.
  *
  * You should have received a copy of the GNU Affero General Public License
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
  */
 
 package org.kaazing.robot.control;
 
 import static java.lang.Integer.parseInt;
 import static java.lang.String.format;
 import static java.util.concurrent.TimeUnit.MILLISECONDS;
 
 import java.io.Writer;
 import java.net.URL;
 
 
 public class TcpRobotControl implements RobotControl {
 
     private static final Pattern HEADER_PATTERN = Pattern.compile("([a-z\\-]+):([^\n]+)");
     private static final Charset UTF_8 = Charset.forName("UTF-8");
 
     private final URL location;
     private URLConnection connection;
 
     public TcpRobotControl(URL location) {
         this. = location;
     }
 
     @Override
     public void connect() throws Exception {
          = .openConnection();
         .connect();
     }
 
     @Override
     public void disconnect() throws Exception {
 
         if ( != null) {
             try {
                 if ( instanceof Closeable) {
                     ((Closeable).close();
                 }
                 else {
                     try {
                         .getInputStream().close();
                     }
                     catch (IOException e) {
                         // ignore
                     }
 
                     try {
                         .getOutputStream().close();
                     }
                     catch (IOException e) {
                         // ignore
                     }
                 }
             }
             finally {
                  = null;
             }
        }
    }
    @Override
    public void writeCommand(Command commandthrows Exception {
        checkConnected();
        switch (command.getKind()) {
        case :
            writecommand((PrepareCommandcommand);
            break;
        case :
            writeCommand((StartCommandcommand);
            break;
        case :
            writeCommand((AbortCommandcommand);
            break;
        default:
            throw new IllegalArgumentException("Urecognized command kind: " + command.getKind());
        }
    }
    @Override
    public CommandEvent readEvent() throws Exception {
        // defaults to infinite
        return readEvent(0, );
    }
    @Override
    public CommandEvent readEvent(int timeoutTimeUnit unitthrows Exception {
        checkConnected();
        .setReadTimeout((intunit.toMillis(timeout));
        InputStream bytesIn = .getInputStream();
        CharsetDecoder decoder = .newDecoder();
        BufferedReader textIn = new BufferedReader(new InputStreamReader(bytesIndecoder));
        String eventType = textIn.readLine();
        switch (eventType.charAt(0)) {
        case 'P':
            if ("PREPARED".equals(eventType)) {
                return readPreparedEvent(textIn);
            }
            break;
        case 'S':
            if ("STARTED".equals(eventType)) {
                return readStartedEvent(textIn);
            }
            break;
        case 'E':
            if ("ERROR".equals(eventType)) {
                return readErrorEvent(textIn);
            }
            break;
        case 'F':
            if ("FINISHED".equals(eventType)) {
                return readFinishedEvent(textIn);
            }
            break;
        }
        throw new IllegalStateException("Invalid protocol frame: " + eventType);
    }
    private void checkConnected() throws Exception {
        if ( == null) {
            throw new IllegalStateException("Not connected");
        }
    }
    private void writecommand(PrepareCommand preparethrows Exception {
        OutputStream bytesOut = .getOutputStream();
        CharsetEncoder encoder = .newEncoder();
        Writer textOut = new OutputStreamWriter(bytesOutencoder);
        String name = prepare.getName();
        String script = prepare.getScript();
        // note: this assumes bytes-length == string-length (ASCII)
        int length = script.length();
        textOut.append("PREPARE\n");
        textOut.append(format("name:%s\n"name));
        // assume v2 script format by default
        textOut.append("content-type:text/x-robot-2\n");
        textOut.append(format("content-length:%d\n"length));
        textOut.append("\n");
        textOut.append(script);
        textOut.flush();
    }
    private void writeCommand(StartCommand startthrows Exception {
        OutputStream bytesOut = .getOutputStream();
        CharsetEncoder encoder = .newEncoder();
        Writer textOut = new OutputStreamWriter(bytesOutencoder);
        String name = start.getName();
        textOut.append("START\n");
        textOut.append(format("name:%s\n"name));
        textOut.append("\n");
        textOut.flush();
    }
    private void writeCommand(AbortCommand abortthrows IOExceptionCharacterCodingException {
        OutputStream bytesOut = .getOutputStream();
        CharsetEncoder encoder = .newEncoder();
        Writer textOut = new OutputStreamWriter(bytesOutencoder);
        String name = abort.getName();
        textOut.append("ABORT\n");
        textOut.append(format("name:%s\n"name));
        textOut.append("\n");
        textOut.flush();
    }
    private PreparedEvent readPreparedEvent(BufferedReader textInthrows IOException {
        PreparedEvent prepared = new PreparedEvent();
        String line;
        do {
            line = textIn.readLine();
            Matcher matcher = .matcher(line);
            if (matcher.matches()) {
                String headerName = matcher.group(1);
                String headerValue = matcher.group(2);
                switch (headerName.charAt(0)) {
                case 'n':
                    if ("name".equals(headerName)) {
                        prepared.setName(headerValue);
                    }
                    break;
                default:
                    throw new IllegalStateException("Unrecognized event header: " + headerName);
                }
            }
        } while (!line.isEmpty());
        return prepared;
    }
    private StartedEvent readStartedEvent(BufferedReader textInthrows IOException {
        StartedEvent started = new StartedEvent();
        String line;
        do {
            line = textIn.readLine();
            Matcher matcher = .matcher(line);
            if (matcher.matches()) {
                String headerName = matcher.group(1);
                String headerValue = matcher.group(2);
                switch (headerName.charAt(0)) {
                case 'n':
                    if ("name".equals(headerName)) {
                        started.setName(headerValue);
                    }
                    break;
                default:
                    throw new IllegalStateException("Unrecognized event header: " + headerName);
                }
            }
        } while (!line.isEmpty());
        return started;
    }
    private FinishedEvent readFinishedEvent(BufferedReader textInthrows IOException {
        FinishedEvent finished = new FinishedEvent();
        String line;
        int length = -1;
        do {
            line = textIn.readLine();
            Matcher matcher = .matcher(line);
            if (matcher.matches()) {
                String headerName = matcher.group(1);
                String headerValue = matcher.group(2);
                switch (headerName.charAt(0)) {
                case 'c':
                    if ("content-length".equals(headerName)) {
                        length = parseInt(headerValue);
                    }
                    break;
                case 'n':
                    if ("name".equals(headerName)) {
                        finished.setName(headerValue);
                    }
                    break;
                default:
                    throw new IllegalStateException("Unrecognized event header: " + headerName);
                }
            }
        } while (!line.isEmpty());
        // note: this assumes bytes-length == string-length (ASCII)
        // note: zero-length script should be non-null
        if (length >= 0) {
            finished.setScript(readContent(textInlength));
        }
        return finished;
    }
    private ErrorEvent readErrorEvent(BufferedReader textInthrows IOException {
        ErrorEvent error = new ErrorEvent();
        String line;
        int length = 0;
        do {
            line = textIn.readLine();
            Matcher matcher = .matcher(line);
            if (matcher.matches()) {
                String headerName = matcher.group(1);
                String headerValue = matcher.group(2);
                switch (headerName.charAt(0)) {
                case 'c':
                    if ("content-length".equals(headerName)) {
                        length = parseInt(headerValue);
                    }
                    break;
                case 'n':
                    if ("name".equals(headerName)) {
                        error.setName(headerValue);
                    }
                    break;
                case 's':
                    if ("summary".equals(headerName)) {
                        error.setSummary(headerValue);
                    }
                    break;
                default:
                    throw new IllegalStateException("Unrecognized event header: " + headerName);
                }
            }
        } while (!line.isEmpty());
        // note: this assumes bytes-length == string-length (ASCII)
        if (length > 0) {
            error.setDescription(readContent(textInlength));
        }
        return error;
    }
    private String readContent(final BufferedReader textInfinal int lengththrows IOException {
        final char[] content = new char[length];
        int bytesRead = 0;
        do {
            int result = textIn.read(contentbytesReadlength - bytesRead);
            if (result == -1) {
                throw new EOFException("EOF detected before all content read");
            }
            bytesRead += result;
        } while (bytesRead != length);
        return new String(content);
    }
New to GrepCode? Check out our FAQ X