Creates the i/o handler and nio acceptor; ports and addresses are bound.

@throws IOException
487561
@Override
    public void afterPropertiesSet() throws Exception {
        // create the nio acceptor
        acceptor = new NioSocketAcceptor(Runtime.getRuntime().availableProcessors() * 4);
        acceptor.addListener(new IoServiceListener() {

            @Override
            public void serviceActivated(IoService service) throws Exception {
                //log.debug("serviceActivated: {}", service);
            }

            @Override
            public void serviceIdle(IoService service, IdleStatus idleStatus) throws Exception {
                //logger.debug("serviceIdle: {} status: {}", service, idleStatus);
            }

            @Override
            public void serviceDeactivated(IoService service) throws Exception {
                //log.debug("serviceDeactivated: {}", service);
            }

            @Override
            public void sessionCreated(IoSession session) throws Exception {
                log.debug("sessionCreated: {}", session);
                //log.trace("Acceptor sessions: {}", acceptor.getManagedSessions());
            }

            @Override
            public void sessionClosed(IoSession session) throws Exception {
                log.debug("sessionClosed: {}", session);
            }

            @Override
            public void sessionDestroyed(IoSession session) throws Exception {
                //log.debug("sessionDestroyed: {}", session);
            }

        });
        // configure the acceptor
        SocketSessionConfig sessionConf = acceptor.getSessionConfig();
        sessionConf.setReuseAddress(true);
        sessionConf.setTcpNoDelay(true);
        sessionConf.setSendBufferSize(sendBufferSize);
        sessionConf.setReadBufferSize(receiveBufferSize);
        // prevent the background blocking queue
        sessionConf.setUseReadOperation(false);
        // seconds
        sessionConf.setWriteTimeout(writeTimeout);
        // set an idle time in seconds
        if (idleTimeout > 0) {
            sessionConf.setIdleTime(IdleStatus.BOTH_IDLE, idleTimeout);
        }
        // close sessions when the acceptor is stopped
        acceptor.setCloseOnDeactivation(true);
        // requested maximum length of the queue of incoming connections
        acceptor.setBacklog(64);
        acceptor.setReuseAddress(true);
        // instance the websocket handler
        if (ioHandler == null) {
            ioHandler = new WebSocketHandler();
        }
        log.trace("I/O handler: {}", ioHandler);
        acceptor.setHandler(ioHandler);
        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
        // if handling wss init the config
        SslFilter sslFilter = null;
        if (secureConfig != null) {
            try {
                sslFilter = secureConfig.getSslFilter();
                chain.addFirst("sslFilter", sslFilter);
            } catch (Exception e) {
                log.warn("SSL configuration failed, websocket will not be secure", e);
            }
        }
        if (log.isTraceEnabled()) {
            chain.addLast("logger", new LoggingFilter());
        }
        // add the websocket codec factory
        chain.addLast("protocol", new ProtocolCodecFilter(new WebSocketCodecFactory()));
        if (addresses.isEmpty()) {
            if (sslFilter != null) {
                log.info("WebSocket (wss) will be bound to port {}", port);
            } else {
                log.info("WebSocket (ws) will be bound to port {}", port);
            }
            acceptor.bind(new InetSocketAddress(port));
        } else {
            if (sslFilter != null) {
                log.info("WebSocket (wss) will be bound to {}", addresses);
            } else {
                log.info("WebSocket (ws) will be bound to {}", addresses);
            }
            try {
                // loop through the addresses and bind
                Set<InetSocketAddress> socketAddresses = new HashSet<InetSocketAddress>();
                for (String addr : addresses) {
                    if (addr.indexOf(':') != -1) {
                        String[] parts = addr.split(":");
                        socketAddresses.add(new InetSocketAddress(parts[0], Integer.valueOf(parts[1])));
                    } else {
                        socketAddresses.add(new InetSocketAddress(addr, port));
                    }
                }
                log.debug("Binding to {}", socketAddresses.toString());
                acceptor.bind(socketAddresses);
            } catch (Exception e) {
                log.warn("Exception occurred during resolve / bind", e);
            }
        }
        log.info("Started {} websocket transport. Timeouts - idle: {} write: {}", (isSecure() ? "secure" : ""), idleTimeout, writeTimeout);
        if (log.isDebugEnabled()) {
            log.debug("Acceptor sizes - send: {} recv: {}", acceptor.getSessionConfig().getSendBufferSize(), acceptor.getSessionConfig().getReadBufferSize());
        }
    }
456464
private void initializePort() throws ChannelException {
        try {
            this.endPoint.initServerSocket();
        } catch (IOException ioe) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "TCP Channel: " + getExternalName() + "- Problem occurred while initializing TCP Channel: " + ioe.getMessage());
            }
            throw new ChannelException("TCP Channel: " + getExternalName() + "- Problem occurred while starting channel: " + ioe.getMessage());
        } catch (RetryableChannelException e) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "TCP Channel: " + getExternalName() + "- Problem occurred while starting TCP Channel: " + e.getMessage());
            }
            throw e;
        }

        // add property to config to provide actual port used (could be ephemeral
        // port if '0' passed in)
        this.channelData.getPropertyBag().put(TCPConfigConstants.LISTENING_PORT, String.valueOf(this.endPoint.getListenPort()));
    }
563351
private void prepareRootFhAndNfsPort() throws IOException {

        if (!_prepareLock.tryLock()) {
            return;
        }

        try {
            _port = getNfsPortFromServer();
            _rpcWrapper.setPort(_port);
            _rootFileHandle = lookupRootHandle();
        } finally {
            _prepareLock.unlock();
        }
    }
1336019
public void startup() throws Throwable
   {
      if (handlerClassName == null || handlerClassName.trim().equals(""))
         throw new IllegalStateException("HandlerClassName isn't defined");

      shutdown();

      ClassLoader cl = classLoader;

      if (cl == null)
         cl = EISServer.class.getClassLoader();

      Class handler = Class.forName(handlerClassName, true, cl);

      if (!Handler.class.isAssignableFrom(handler))
         throw new IllegalArgumentException("The specified handler class doesn't implement the interface");

      HandlerServer handlerServer = new HandlerServer(host, port, handler);
      handlerServer.start();

      handlerServers.put(getKey(), handlerServer);
   }
1044857
public C accept() throws IOException {
		try {
			synchronized(this){
				if (connState != CONN_STATE_READY_FOR_ACCEPT) {
					throw new IOException("bind needs to be called before accept (1), current state =" + connState);
				}
				logger.info("starting accept");
				if (requested.peek() == null){
					wait();
				}
			}
			C endpoint = requested.poll();
			logger.info("connect request received");
			endpoint.accept();
			return endpoint;
		} catch (Exception e) {
			throw new IOException(e);
		}
	}
65012
protected void initialize() throws IOException {
    // set service-level authorization security policy
    if (serviceAuthEnabled =
        getConf().getBoolean(
            ServiceAuthorizationManager.SERVICE_AUTHORIZATION_CONFIG, false)) {
      PolicyProvider policyProvider =
        (PolicyProvider)(ReflectionUtils.newInstance(
            getConf().getClass(PolicyProvider.POLICY_PROVIDER_CONFIG,
                HDFSPolicyProvider.class, PolicyProvider.class),
            getConf()));
      SecurityUtil.setPolicy(new ConfiguredPolicy(getConf(), policyProvider));
    }

    // This is a check that the port is free
    // create a socket and bind to it, throw exception if port is busy
    // This has to be done before we are reading Namesystem not to waste time and fail fast
    NetUtils.isSocketBindable(getClientProtocolAddress(getConf()));
    NetUtils.isSocketBindable(getDNProtocolAddress(getConf()));
    NetUtils.isSocketBindable(getHttpServerAddress(getConf()));

    long serverVersion = ClientProtocol.versionID;
    this.clientProtocolMethodsFingerprint = ProtocolSignature
        .getMethodsSigFingerPrint(ClientProtocol.class, serverVersion);

    myMetrics = new NameNodeMetrics(getConf(), this);

    this.clusterName = getConf().get(FSConstants.DFS_CLUSTER_NAME);
    this.namesystem = new FSNamesystem(this, getConf());
    // HACK: from removal of FSNamesystem.getFSNamesystem().
    JspHelper.fsn = this.namesystem;

    this.startDNServer();
    startHttpServer(getConf());
  }
305981
private Socket createSocket() throws IOException {
        final ManagedSocketFactory socketFactory = this.socketBindingManager.getSocketFactory();
        final Socket socket = socketFactory.createSocket(this.name);
        // if the outbound binding specifies the source to use, then bind this socket to the
        // appropriate source
        final SocketAddress sourceSocketAddress = this.getOptionalSourceSocketAddress();
        if (sourceSocketAddress != null) {
            socket.bind(sourceSocketAddress);
        }
        return socket;
    }
442596
private void doSocketConnect(InetSocketAddress addr) throws IOException{
        SocketChannel sock = createSock();
        registerAndConnect(sock, addr);
    }
102104
public void init() throws IOException {
    Injector injector = Guice.createInjector(
        new ConfigModule(conf),
        new ZKModule(),
        new DiscoveryModules().getDistributedModules(),
        new TransactionModules().getDistributedModules(),
        new TransactionClientModule()
    );

    zkClient = injector.getInstance(ZKClientService.class);
    zkClient.startAndWait();
    txClient = injector.getInstance(TransactionServiceClient.class);

    createTableIfNotExists(conf, TABLE, new byte[][]{ FAMILY });
    conn = HConnectionManager.createConnection(conf);
  }
1161262
@Override
	public Connector createConnector(String address, int port,
				     String protocol) {

        Connector connector = null;

	if (address != null) {
	    /*
	     * InetAddress.toString() returns a string of the form
	     * "<hostname>/<literal_IP>". Get the latter part, so that the
	     * address can be parsed (back) into an InetAddress using
	     * InetAddress.getByName().
	     */
	    int index = address.indexOf('/');
	    if (index != -1) {
		address = address.substring(index + 1);
	    }
	}

	if (log.isDebugEnabled()) {
            log.debug("Creating connector for address='" +
		      ((address == null) ? "ALL" : address) +
		      "' port='" + port + "' protocol='" + protocol + "'");
	}

        try {

            if (protocol.equals("ajp")) {
                connector = new Connector("org.apache.jk.server.JkCoyoteHandler");
            } else if (protocol.equals("memory")) {
                connector = new Connector("org.apache.coyote.memory.MemoryProtocolHandler");
            } else if (protocol.equals("http")) {
                connector = new Connector();
            } else if (protocol.equals("https")) {
                connector = new Connector();
                connector.setScheme("https");
                connector.setSecure(true);
                connector.setProperty("SSLEnabled","true");
            } else {
                connector = new Connector(protocol);
            }

            if (address != null) {
                IntrospectionUtils.setProperty(connector, "address", 
                                               "" + address);
            }
            IntrospectionUtils.setProperty(connector, "port", "" + port);

        } catch (Exception e) {
            log.error("Couldn't create connector.");
        } 

        return (connector);

    }
468898
private void setup(final Handler<AsyncResult<Void>> doneHandler) {
    // Retrieve the component context from the coordinator (the current cluster).
    // If the context has changed due to a network configuration change, the
    // internal context and input/output connections will be automatically updated.
    log.debug(String.format("%s - Starting cluster coordination", DefaultComponent.this));
    coordinator.start(new Handler<AsyncResult<Void>>() {
      @Override
      public void handle(AsyncResult<Void> result) {
        if (result.failed()) {
          new DefaultFutureResult<Void>(result.cause()).setHandler(doneHandler);
        } else {
          // We have to make sure the input and output collectors are started
          // simultaneously in order to support circular connections. If both
          // input and output aren't started at the same time then circular
          // connections will never open.
          final CountingCompletionHandler<Void> ioHandler = new CountingCompletionHandler<Void>(2);
          ioHandler.setHandler(new Handler<AsyncResult<Void>>() {
            @Override
            public void handle(AsyncResult<Void> result) {
              if (result.failed()) {
                new DefaultFutureResult<Void>(result.cause()).setHandler(doneHandler);
              } else {
                // Tell the coordinator we're ready for the network to start.
                coordinator.resume();
              }
            }
          });

          output.open(new Handler<AsyncResult<Void>>() {
            @Override
            public void handle(AsyncResult<Void> result) {
              if (result.failed()) {
                log.error(String.format("%s - Failed to open component outputs", DefaultComponent.this), result.cause());
                ioHandler.fail(result.cause());
              } else {
                ioHandler.succeed();
              }
            }
          });

          input.open(new Handler<AsyncResult<Void>>() {
            @Override
            public void handle(AsyncResult<Void> result) {
              if (result.failed()) {
                log.error(String.format("%s - Failed to open component inputs", DefaultComponent.this), result.cause());
                ioHandler.fail(result.cause());
              } else {
                ioHandler.succeed();
              }
            }
          });
        }
      }
    });

    // The resume handler will be called by the coordinator once the
    // network's manager has indicated that all the components in the
    // network have finished setting up their connections.
    coordinator.resumeHandler(new Handler<Void>() {
      @Override
      @SuppressWarnings("unchecked")
      public void handle(Void _) {
        if (!started) {
          started = true;
          log.debug(String.format("%s - Started", DefaultComponent.this, context.component().name(), context.number()));
          List<ComponentHook> hooks = context.component().hooks();
          for (ComponentHook hook : hooks) {
            hook.handleStart(DefaultComponent.this);
          }
          new DefaultFutureResult<Void>((Void) null).setHandler(doneHandler);
        }
      }
    });
  }
108744
@Override
  public void create()
    throws IOException
  {
    Files.createDirectories(_path.getParent());

    if (Files.exists(_path)) {
      throw new IOException(L.l("CREATE for path '{0}' failed, because the file already exists.  CREATE can not override an existing table.",
                                _path));
    }
    
    init();
    /*
    _channel = _path.openFileChannel(StandardOpenOption.CREATE, 
                                     StandardOpenOption.WRITE,
                                     StandardOpenOption.READ);
    
    setFileSize(_path.length());
    
    initImpl();
    */
  }
632917
public static void process(InputStream inputStream, StreamHandler handler) throws IOException {
    LOGGER.trace("process(InputStream, StreamHandler)");
    process(inputStream, handler, new byte[BUFFER_SIZE]);
  }
222034
public void initialize() throws IOException, NotInitializedException {
    logger.debug("Initialising TCPTransportClient. Origin address is [{}] and destination address is [{}]", origAddress, destAddress);
    if (destAddress == null) {
      throw new NotInitializedException("Destination address is not set");
    }
    socketChannel = SelectorProvider.provider().openSocketChannel();

    try {
      if (origAddress != null) {
        socketChannel.socket().bind(origAddress);
      }

      socketChannel.connect(destAddress);
      //PCB added logging
      socketChannel.configureBlocking(BLOCKING_IO);
      getParent().onConnected();
    }
    catch (IOException e) {
      if (origAddress != null) {
        socketChannel.socket().close();
      }
      socketChannel.close();
      throw e;
    }
  }
76203
public void bindAndStart(int port) throws Exception {
        server = new NioServer(new StreamConnectionFactory() {
            @Override
            public ProtobufConnection<Protos.TwoWayChannelMessage> getNewConnection(InetAddress inetAddress, int port) {
                return new ServerHandler(new InetSocketAddress(inetAddress, port), timeoutSeconds).socketProtobufHandler;
            }
        }, new InetSocketAddress(port));
        server.startAsync();
        server.awaitRunning();
    }
558972
public synchronized void prepareSocket() throws IOException {
        if (!prepared) {
            final long fd = getFileDescriptor();
            if (fd == INVALID_SOCKET) {
                throw new AsyncException(AsyncProperties.aio_handle_unavailable);
            }

            channelIdentifier = provider.prepare2(fd, asyncChannelGroup.getCompletionPort());

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "prepareSocket - socket prepared, fd = " + fd
                             + " channel id: " + channelIdentifier + " "
                             + ", local: " + channel.socket().getLocalSocketAddress()
                             + ", remote: " + channel.socket().getRemoteSocketAddress());
            }
            long callid = 0; // init to zero, reset when IO requested

            readIOCB = (CompletionKey) AsyncLibrary.completionKeyPool.get();
            if (readIOCB != null) {
                // initialize the IOCB from the pool
                readIOCB.initializePoolEntry(channelIdentifier, callid);

                writeIOCB = (CompletionKey) AsyncLibrary.completionKeyPool.get();
                if (writeIOCB != null) {
                    // initialize the IOCB from the pool
                    writeIOCB.initializePoolEntry(channelIdentifier, callid);
                } else {
                    writeIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount);
                }
            } else {
                readIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount);
                writeIOCB = new CompletionKey(channelIdentifier, callid, defaultBufferCount);
            }

            provider.initializeIOCB(readIOCB);
            provider.initializeIOCB(writeIOCB);
            prepared = true;
        }
    }
535574
public NioClient init(InetSocketAddress address) {
		try {
			this.channel = SocketChannel.open(address);
		} catch (IOException e) {
			throw new IORuntimeException(e);
		}
		return this;
	}