Open a new connection and wait until connection is ready

@throws DeploymentException
@throws IOException
@throws InterruptedException
518392
public void connect() throws DeploymentException, IOException, InterruptedException {
		final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
		connectLatch = new CountDownLatch(1);
		this.userSession = container.connectToServer(this, endpointURI);
		connectLatch.await(15, TimeUnit.SECONDS);
	}
363056
@Override
  public void startOnInit(DeployService2Impl<I> deploy, Result<I> result)
  {
    deploy.startImpl(result);
  }
691208
protected final WaitForProcess startInternal() throws IOException {
    // Invoke listeners - they can modify this executor
    listeners.beforeStart(this);

    if (builder.command().isEmpty()) {
      throw new IllegalStateException("Command has not been set.");
    }
    validateStreams(streams, readOutput);

    applyEnvironment();
    messageLogger.message(log, getExecutingLogMessage());
    Process process = invokeStart();
    messageLogger.message(log, "Started {}", process);
    ProcessAttributes attributes = getAttributes();

    ExecuteStreamHandler newStreams = streams;
    ByteArrayOutputStream out = null;
    if (readOutput) {
      PumpStreamHandler pumps = (PumpStreamHandler) streams;
      out = new ByteArrayOutputStream();
      newStreams = redirectOutputAlsoTo(pumps, out);
    }
    return startInternal(process, attributes, newStreams, out);
  }
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());
  }
1075677
public boolean waitForConnectionInit() {
        try {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "waitForConnectionInit: waiting for the H2 connection to complete initialization on " + streamId());
            }
            // the connection isn't initialized yet; wait on the init lock
            boolean rc = muxLink.initLock.await(Constants.H2C_UPGRADE_TIMEOUT, java.util.concurrent.TimeUnit.MILLISECONDS);
            if (rc) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "waitForConnectionInit: stop waiting, H2 connection initialized " + streamId());
                }
            } else {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "waitForConnectionInit: stop waiting, timed out waiting for client ");
                }
                muxLink.close(muxLink.initialVC, new ProtocolException("http/2 protocol initialization failed"));
            }
            return rc;
        } catch (InterruptedException e) {
            // server error handled in caller
            return false;
        }
    }
915478
public void join()
        throws InterruptedException
    { 
        for (int l=0;l<_listeners.size();l++)
        {
            HttpListener listener =(HttpListener)_listeners.get(l); 
            if (listener.isStarted() && listener instanceof ThreadPool)
            {
                ((ThreadPool)listener).join();
            }
        }
    }
607334
@Override
    public void waitForFinish() throws IOException
    {
        if (future == null)
        {
            throw new IllegalStateException("not started");
        }
        try
        {
            future.get();
        }
        catch (InterruptedException | ExecutionException ex)
        {
            throw new IOException(ex);
        }
    }
887531
final void activate() throws SQLException {
      for(ConnectionPoolConnection conn : connections) {
         conn.forceRealClose();
         conn.realOpen();
         conn.logicalClose(true); //Tests the connection
      }

      if(closeQueue != null) {
         closeQueue.clear();
      }

      availableQueue.clear();
      reopenExecutor.getQueue().clear();

      List<ConnectionPoolConnection> connections = Lists.newArrayListWithCapacity(this.connections.length);
      for(ConnectionPoolConnection connection : this.connections) {
         connections.add(connection);
         connection.state.set(ConnectionPoolConnection.STATE_AVAILABLE);
      }

      isActive = true;
      stats.activate();
      availableQueue.addAll(connections);
   }
1081667
@SuppressWarnings("deprecation")
  void init() throws InterruptedException, IOException {
    long now = System.currentTimeMillis();

    JobConf jobConf = new JobConf(getConf());
    jobConf.setClass("topology.node.switch.mapping.impl",
        StaticMapping.class, DNSToSwitchMapping.class);
    jobConf.set("fs.default.name", "file:///");
    jobConf.set("mapred.job.tracker", "localhost:8012");
    jobConf.setInt("mapred.jobtracker.job.history.block.size", 512);
    jobConf.setInt("mapred.jobtracker.job.history.buffer.size", 512);
    jobConf.setLong("mapred.tasktracker.expiry.interval", 5000);
    jobConf.setInt("mapred.reduce.copy.backoff", 4);
    jobConf.setLong("mapred.job.reuse.jvm.num.tasks", -1);
    jobConf.setUser("mumak");
    jobConf.set("mapred.system.dir", 
        jobConf.get("hadoop.log.dir", "/tmp/hadoop-"+jobConf.getUser()) + "/mapred/system");
    jobConf.set("mapred.jobtracker.taskScheduler", JobQueueTaskScheduler.class.getName());
    
    FileSystem lfs = FileSystem.getLocal(getConf());
    Path logPath =
      new Path(System.getProperty("hadoop.log.dir")).makeQualified(lfs);
    jobConf.set("mapred.system.dir", logPath.toString());
    jobConf.set("hadoop.job.history.location", (new Path(logPath, "history")
        .toString()));
    
    jt = SimulatorJobTracker.startTracker(jobConf, now, this);
    jt.offerService();
    
    // max Map/Reduce tasks per node
    int maxMaps = getConf().getInt("mapred.tasktracker.map.tasks.maximum",
        DEFAULT_MAP_SLOTS_PER_NODE);
    int maxReduces = getConf().getInt(
        "mapred.tasktracker.reduce.tasks.maximum",
        DEFAULT_REDUCE_SLOTS_PER_NODE);

    MachineNode defaultNode = new MachineNode.Builder("default", 2)
        .setMapSlots(maxMaps).setReduceSlots(maxReduces).build();
    ZombieCluster cluster = new ZombieCluster(new Path(topologyFile), 
        defaultNode, jobConf);
    long firstJobStartTime = now + 60000;
    JobStoryProducer jobStoryProducer = new SimulatorJobStoryProducer(
        new Path(traceFile), cluster, firstJobStartTime, jobConf);
    
    jc = new SimulatorJobClient(jt, jobStoryProducer);
    queue.addAll(jc.init(firstJobStartTime));

    // create TTs based on topology.json     
    startTaskTrackers(cluster, now);
    
    terminateTime = getConf().getLong("mumak.terminate.time", Long.MAX_VALUE);
    if (terminateTime <= 0) {
      throw new IllegalArgumentException("Terminate time must be positive: "
          + terminateTime);
    }
  }
1250530
public void start() throws InterruptedException {
    logger.debug("Staring client TLSTransportClient {} ", socketDescription);
    if (isConnected()) {
      logger.debug("Already connected TLSTransportClient {} ", socketDescription);
      return;
    }

    workerGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();
        pipeline.addLast("decoder", new DiameterMessageDecoder(parentConnection, parser));
        pipeline.addLast("msgHandler", new DiameterMessageHandler(parentConnection, false));
        pipeline.addLast("startTlsInitiator", new StartTlsInitiator(config, TLSTransportClient.this));
        pipeline.addLast("encoder", new DiameterMessageEncoder(parser));
        pipeline.addLast("inbandWriter", new InbandSecurityHandler());
      }
    });

    this.channel = bootstrap.remoteAddress(destAddress).connect().sync().channel();

    parentConnection.onConnected();

    logger.debug("Started TLS Transport on Socket {}", socketDescription);
  }
1232532
@Override
  public ServerImpl start() throws IOException {
    synchronized (lock) {
      checkState(!started, "Already started");
      checkState(!shutdown, "Shutting down");
      // Start and wait for any ports to actually be bound.

      ServerListenerImpl listener = new ServerListenerImpl();
      for (InternalServer ts : transportServers) {
        ts.start(listener);
        activeTransportServers++;
      }
      executor = Preconditions.checkNotNull(executorPool.getObject(), "executor");
      started = true;
      return this;
    }
  }
267016
private URLConnection openConnection() throws IOException {
		return (null == this.proxy) ? url.openConnection() : url.openConnection(this.proxy);
	}
362146
public void connect() throws IOException, DeploymentException {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        container.connectToServer(this, wssUri);
        log.debug("client connected to the server: {}", wssUri);
    }
863428
private Connection<CL> waitForConnection(int timeout) throws ConnectionException {
        Connection<CL> connection = null;
        long startTime = System.currentTimeMillis();
        try {
            blockedThreads.incrementAndGet();
            connection = availableConnections.poll(timeout, TimeUnit.MILLISECONDS);
            if (connection != null)
                return connection;
            
            throw new PoolTimeoutException("Timed out waiting for connection")
                .setHost(getHost())
                .setLatency(System.currentTimeMillis() - startTime);
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new InterruptedOperationException("Thread interrupted waiting for connection")
                .setHost(getHost())
                .setLatency(System.currentTimeMillis() - startTime);
        }
        finally {
            blockedThreads.decrementAndGet();
        }
    }
1218263
public void open(Connection conn, String fileName, long filePosition, final int serverId, boolean nonBlocking)
                                                                                                                  throws IOException {
        try {
            this.conn = conn;
            Class<?> connClazz = Class.forName("com.mysql.jdbc.ConnectionImpl");
            Object unwrapConn = unwrapConnection(conn, connClazz);
            if (unwrapConn == null) {
                throw new IOException("Unable to unwrap " + conn.getClass().getName()
                                      + " to com.mysql.jdbc.ConnectionImpl");
            }

            // Get underlying IO streams for network communications.
            Object connIo = getDeclaredField(unwrapConn, connClazz, "io");
            if (connIo == null) {
                throw new IOException("Get null field:" + conn.getClass().getName() + "#io");
            }
            mysqlOutput = (OutputStream) getDeclaredField(connIo, connIo.getClass(), "mysqlOutput");
            mysqlInput = (InputStream) getDeclaredField(connIo, connIo.getClass(), "mysqlInput");

            if (filePosition == 0) filePosition = BIN_LOG_HEADER_SIZE;
            sendBinlogDump(fileName, filePosition, serverId, nonBlocking);
            position = 0;
        } catch (IOException e) {
            close(); /* Do cleanup */
            logger.error("Error on COM_BINLOG_DUMP: file = " + fileName + ", position = " + filePosition);
            throw e;
        } catch (ClassNotFoundException e) {
            close(); /* Do cleanup */
            throw new IOException("Unable to load com.mysql.jdbc.ConnectionImpl", e);
        }
    }
1282970
public void open() throws IOException
    {
        if (_listen == null)
        {
            _listen = newServerSocket(_address, _acceptQueueSize);

            if (_address == null)
                _address = new InetAddrPort(_listen.getInetAddress(), _listen.getLocalPort());
            else
            {
                if (_address.getInetAddress() == null)
                        _address.setInetAddress(_listen.getInetAddress());
                if (_address.getPort() == 0) _address.setPort(_listen.getLocalPort());
            }

            _soTimeOut = getMaxIdleTimeMs();
            if (_soTimeOut >= 0) _listen.setSoTimeout(_soTimeOut);
        }
    }
487949
@Override
  public void connect() {
    if (!canRun.compareAndSet(true, false) || clientBase.isDone()) {
      throw new IllegalStateException("There is already a connection thread running for " + this.clientBase);
    }
    executorService.execute(clientBase);
    logger.info("New connection executed: {}", this.clientBase);
  }