TcpClientController.java

    1/*******************************************************************************
    2 * Copyright (c) 2009, 2010 Mountainminds GmbH & Co. KG and Contributors
    3 * All rights reserved. This program and the accompanying materials
    4 * are made available under the terms of the Eclipse Public License v1.0
    5 * which accompanies this distribution, and is available at
    6 * http://www.eclipse.org/legal/epl-v10.html
    7 *
    8 * Contributors:
    9 *    Marc R. Hoffmann - initial API and implementation
   10 *    
   11 *******************************************************************************/
   12package org.jacoco.agent.rt.controller;
   13
   14import java.io.IOException;
   15import java.net.Socket;
   16
   17import org.jacoco.agent.rt.IExceptionLogger;
   18import org.jacoco.core.runtime.AgentOptions;
   19import org.jacoco.core.runtime.IRuntime;
   20
   21/**
   22 * @author Marc R. Hoffmann
   23 * @version 0.4.1.20101007204400
   24 */
   25public class TcpClientController implements IAgentController {
   26
   27    private final IExceptionLogger logger;
   28
   29    private TcpConnection connection;
   30
   31    private Thread worker;
   32
   33    public TcpClientController(final IExceptionLogger logger) {
   34        this.logger = logger;
   35    }
   36
   37    public void startup(final AgentOptions options, final IRuntime runtime)
   38            throws IOException {
   39        final Socket socket = createSocket(options);
   40        connection = new TcpConnection(socket, runtime);
   41        connection.init();
   42        worker = new Thread(new Runnable() {
   43            public void run() {
   44                try {
   45                    connection.run();
   46                } catch (IOException e) {
   47                    logger.logExeption(e);
   48                }
   49            }
   50        });
   51        worker.setName(getClass().getName());
   52        worker.setDaemon(true);
   53        worker.start();
   54    }
   55
   56    public void shutdown() throws Exception {
   57        connection.close();
   58        worker.join();
   59    }
   60
   61    public void writeExecutionData() throws IOException {
   62        connection.writeExecutionData();
   63    }
   64
   65    /**
   66     * Open a socket based on the given configuration.
   67     * 
   68     * @param options
   69     *            address and port configuration
   70     * @return opened socket
   71     * @throws IOException
   72     */
   73    protected Socket createSocket(final AgentOptions options)
   74            throws IOException {
   75        return new Socket(options.getAddress(), options.getPort());
   76    }
   77
   78}