Convenience method, so that we don't open a new connection when using this
method from within another method. Otherwise every API invocation incurs
the overhead of opening/closing a TCP connection.
438277
private boolean isFile(FTPClient client, Path file) {
    try {
      return !getFileStatus(client, file).isDir();
    } catch (FileNotFoundException e) {
      return false; // file does not exist
    } catch (IOException ioe) {
      throw new FTPException("File check failed", ioe);
    }
  }
905675
ConnectionWrapper obtainConnection() {
		synchronized (allConnections) {
			//fails if connection pool not started
			if (!availableConnections.isEmpty()) {
				//retrieve and remove first connection from list
				//  since released connections are added to the back, connections will rotate
				ConnectionWrapper connWrap = (ConnectionWrapper) availableConnections.remove(0);
				usedConnections.add(connWrap);
				if (usedConnections.size() > maxNrOfConcurrentConnectionsCounted) {
					maxNrOfConcurrentConnectionsCounted = usedConnections.size();
				}
				return connWrap;
			} else {
				//create one if max not reached
				//this also restores lost connections
				if ((allConnections.size() < initialNrofConnections) || (allConnections.size() < maxNrofConnections)) {
					try {
						ConnectionWrapper connWrap = createConnectionWrapper(dbUrl, dbUsername, dbUserpassword);

						allConnections.add(connWrap);
						usedConnections.add(connWrap);

						System.out.println(new LogEntry("Creating new Connection, now " + allConnections.size() + " in use"));

						return connWrap;
					} catch (SQLException sqle) {
						//happens if db unreachable
						//connection will be lost for the time being
						nrofErrors++;
						System.out.println(new LogEntry("Cannot create new connection to " + dbUrl + " unreachable or useless connection settings", sqle));
						throw new ResourceException("Cannot create new connection to " + dbUrl + " unreachable or useless connection settings", sqle);
					}
				} else {
					System.out.println(new LogEntry("maximum nr of connections (" + maxNrofConnections + ") reached while Application demands another"));
				}
				return null;
			}
		}
	}
255358
public void processNewConnection(SocketIOChannel socket) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "processNewConnection");
        }

        VirtualConnection vc = vcf.createConnection();
        TCPConnLink bc = (TCPConnLink) tcpChannel.getConnectionLink(vc);
        TCPReadRequestContextImpl bcRead = bc.getTCPReadConnLink();

        bc.setSocketIOChannel(socket);

        ConnectionDescriptor cd = vc.getConnectionDescriptor();
        Socket s = socket.getSocket();
        InetAddress remote = s.getInetAddress();
        InetAddress local = s.getLocalAddress();

        if (cd != null) {
            cd.setAddrs(remote, local);
        } else {
            ConnectionDescriptorImpl cdi = new ConnectionDescriptorImpl(remote, local);

            vc.setConnectionDescriptor(cdi);
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Processing Connection: " + vc.getConnectionDescriptor());
        }

        int rc = vc.attemptToSetFileChannelCapable(VirtualConnection.FILE_CHANNEL_CAPABLE_ENABLED);
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "FileChannelCapable set in VC to: " + rc);
        }

        bcRead.setJITAllocateSize(bc.getConfig().getNewConnectionBufferSize());
        int timeout = bc.getConfig().getInactivityTimeout();
        if (timeout == ValidateUtils.INACTIVITY_TIMEOUT_NO_TIMEOUT) {
            timeout = TCPRequestContext.NO_TIMEOUT;
        }

        // Set a chain property that is used later by the SSL channel on Z only
        // (CRA)
        // This is needed to support a Z unique client certificate mapping function
        // which may be moved to non Z platforms in the future.
        vc.getStateMap().put("REMOTE_ADDRESS", bc.getRemoteAddress().getHostAddress());

        bcRead.read(1, cc, true, timeout);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "processNewConnection");
        }
    }
471804
public static Closeable closeableFrom(@WillNotClose @Nullable final Connection connection) {
        return closeableFrom(connection, Connection::close);
    }
1251091
public CloseableHttpClient createHttpConnection() {
    LOG.trace("HTTP build new connection based on connection pool");
    return HttpClients
            .custom()
            .setRetryHandler(getRetryHandler())
            .setConnectionManager(connectionPool)
            .setDefaultRequestConfig(rConfig)
            .setKeepAliveStrategy(myStrategy)
            .build();
  }
508006
public T requestInstance() {
		T a;
		if( unused.size() > 0 ) {
			a = unused.pop();
		} else {
			a = createInstance();
		}
		return a;
	}
658595
private void freeMicroConnection(MicroPooledConnection microConn) { 


		Connection tempConn=null;
		try {
			tempConn = microConn.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(tempConn!=null){
			int totalSize=getConnCount();
			if(totalSize<=getMinSize()){
				pool.add(tempConn); 
			}
		}
    }
187776
public Boolean close() {
        _isClosing = true;
        boolean closeResult = true;
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()){
            Tr.debug(tc, "close, Initial read outstanding : " + _isInitialRead);
        }
        
        if(_isInitialRead){
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()){
                Tr.debug(tc, "close, Cancelling any outstanding read");
            }
            
            _tcpContext.getReadInterface().read(1, _tcpChannelCallback, false, TCPReadRequestContext.IMMED_TIMEOUT);
            
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "close, Call to cancel complete");
            }
            
            //This seems strange, but what happens during the timeout it will be set to false.
            //If it's false we don't want to do the wait since it's been called in line.
            //If it's true we will want to wait until the timeout has been processed
            if(_isInitialRead){
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "close, Timeout has been called, waiting for it to complete");
                }
                closeResult = true;
            } else {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()){
                    Tr.debug(tc, "close, No read outstanding, no reason to call cancel");
                }
                closeResult = false;
            }
        } else {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()){
                Tr.debug(tc, "close, No read outstanding, no reason to call cancel");
            }
            closeResult = false;
        }
        
        if(_rl != null){
            if(!this.isAlldataReadCalled()) {
                try {

                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()){
                        Tr.debug(tc, "close, We are now closed, calling the ReadListener onAllDataRead");
                    }
                    this.setAlldataReadCalled(true);
                    _rl.onAllDataRead();
                } catch (IOException ioe) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()){
                        Tr.debug(tc, "close, Encountered an exception while calling onAllDAtaRead : " + ioe);
                    }
                }
            }
        }
        
        return closeResult;
    }
188815
public RequestSender request(HttpMethod method) {
		Objects.requireNonNull(method, "method");
		TcpClient tcpConfiguration = tcpConfiguration().bootstrap(b -> HttpClientConfiguration.method(b, method));
		return new HttpClientFinalizer(tcpConfiguration);
	}
238182
@Override
    protected boolean performRequest() {

        SocketChannel sc = null;
        boolean closeOnError = false;

        // If we were woken up because we have work to do, do it.
        Set<SelectionKey> keySet = this.selector.selectedKeys();
        Iterator<SelectionKey> keyIterator = keySet.iterator();
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(this, tc, "performRequest - processing " + keySet.size() + " items");
        }

        while (keyIterator.hasNext()) {
            closeOnError = false;

            // If we get exceptions repeatedly, we may need to take a break for a number of reasons
            if (numExceptions >= 3100) {
                // if we don't recover after 290 more seconds, wait for 10 minutes
                if (pauseAccept()) {
                    resetExceptions(); // clear exceptions if we weren't interrupted
                }
                continue;
            } else if (numExceptions >= 200) {
                // if we get exceptions repeatedly, wait a tenth to give
                // other threads some time. It should take about 10 seconds for
                // us to get up to 200 exceptions (via trace analysis).
                if (numExceptions == 1500) {
                    FFDCFilter.processException(new Exception("TCP channel has received 1500 exceptions in a row on the accept selector"),
                                                getClass().getName(), "101", this);
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ie) {
                    // ignore it
                }
            }

            // PK40415 - change audit handling of errors
            SelectionKey key = keyIterator.next();
            TCPPort endPoint = (TCPPort) key.attachment();
            TCPChannel tcpChannel = endPoint.getTCPChannel();

            try {
                // safe remove from set while iterating
                keyIterator.remove();

                // perform accept
                ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

                try {
                    sc = serverSocketChannel.accept();

                    // Configure all inbound channels to be non-blocking
                    if (sc != null) {
                        sc.configureBlocking(false);
                    }

                } catch (IOException ioe) {
                    incrementExceptions();
                    this.numAcceptIOExceptions++;
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                        Tr.event(this, tc, "TCP Channel: " + tcpChannel.getExternalName() + " caught IOException doing accept: " + ioe + " total=" + numExceptions + " count="
                                           + numAcceptIOExceptions);
                    }
                    // Since we could be monitoring several serverSocketChannels, we need
                    // to continue processing even though we got an IOException on this
                    // serverSocketChannel.
                    continue;
                }

                // sometimes the accept can return null. This seems to happen when
                // there is a network problem, and we got notified it was ready to
                // accept, but when we went to do the accept we couldn't complete the accept. If
                // this happens, just skip this and go on
                if (sc == null) {
                    incrementExceptions();
                    this.numAcceptNulls++;
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                        Tr.event(this, tc, "TCP Channel: " + tcpChannel.getExternalName() + " accept() returned null, total=" + numExceptions + " count=" + numAcceptNulls);
                    }
                    continue;
                }

                Socket socket = sc.socket();
                if (!testSocket(sc)) {
                    continue;
                }
                closeOnError = true;

                if (!tcpChannel.verifyConnection(socket)) {
                    closeSocketChannel(sc);

                    // if we made it this far, then the accept worked without exceptions
                    if (0 < this.numExceptions) {
                        resetExceptions();
                    }
                    continue;
                }

                SocketIOChannel ioSocket = null;
                try {
                    ioSocket = tcpChannel.createInboundSocketIOChannel(sc);
                } catch (IOException ioe) {
                    // no FFDC required
                    incrementExceptions();
                    this.numConfigureIOExceptions++;
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                        Tr.event(this, tc, "IOException caught while configuring socket: " + ioe + ", total=" + numExceptions + " count=" + numConfigureIOExceptions);
                    }
                    closeSocketChannel(sc);
                    continue;
                }
                endPoint.processNewConnection(ioSocket);

            } catch (CancelledKeyException cke) {
                // no FFDC required
                // Should only get this if the socket was closed. Therefore
                // log error and continue processing
                incrementExceptions();
                this.numCancelledKeys++;
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Tr.event(this, tc, "Cancelled key exception found, cke=" + cke + " total=" + numExceptions + " count=" + numCancelledKeys);
                }
                continue;
            } catch (Throwable t) {
                // don't leak sockets if we can't proceed after the accept
                if (closeOnError) {
                    closeSocketChannel(sc);
                }
                // the catcher of the RTE will do the FFDC
                throw new RuntimeException(t);
            }

            // if we made it this far, then the accept worked without exceptions
            if (0 < this.numExceptions) {
                resetExceptions();
            }
        } // end-while
        return false;
    }
869682
protected CloseableHttpClient createTrustingHttpClient() throws IOException {
    try {
      HttpClientBuilder builder = HttpClientBuilder.create();
      SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustAllStrategy()).build();
      builder.setSSLContext(sslContext);

      HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

      SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
      Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
          .register("http", PlainConnectionSocketFactory.getSocketFactory())
          .register("https", sslSocketFactory)
          .build();

      PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
      builder.setConnectionManager(connMgr);
      return builder.build();
    }
    catch (Exception e) {
      throw new IOException(e);
    }
  }
155413
private void cleanupConnection(TaskListener listener) {
        // we might be called multiple times from multiple finally/catch block, 
        if (connection!=null) {
            connection.close();
            connection = null;
            listener.getLogger().println(Messages.SSHLauncher_ConnectionClosed(getTimestamp()));
        }
    }
10118
@Override
	protected void onConnectionClose()
    {
    	super.onConnectionClose();
    	
    	try
        {
        	if (transport != null && !transport.isClosed())
        	{
	            log.debug("#"+id+" Closing transport");
	            this.transport.close();
        	}
        }
        catch (Exception e)
        {
            log.error("Could not close transport",e);
        }
    }
240889
@Override
    public void close(VirtualConnection inVC, Exception e) {

        // This H2InboundLink.close method should only get called from the H2HttpInboundLinkWrap.close method.
        // for this reason, if we sync this method, then if a stream changes state while we are looking at it, we should
        // be able to do the close when that stream closing causes this close method to be called.

        // the device link close should always use the initial VC that this object was created with, so inVC will be ignored.

        synchronized (linkStatusSync) {

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "close(vc,e): :linkstatus: is: " + linkStatus + " :close: H2InboundLink hc: " + this.hashCode());
            }

            if ((linkStatus == LINK_STATUS.CLOSING) || (linkStatus == LINK_STATUS.GOAWAY_SENDING)
                || (linkStatus == LINK_STATUS.WAIT_TO_SEND_GOAWAY)) {
                // another thread is in charge of closing, or another thread has already armed the future to close
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "close(vc,e): returning: close of muxLink is being done on a differnt thread" + " :close: H2InboundLink hc: " + this.hashCode());
                }
                return;
            }

            if (e == null) {
                // Attempt to close down cleanly if all streams are closed.

                //Determine if all streams are in half closed or closed state
                //If not, do nothing and return
                //If so, look to see if the GoAway frame has been sent
                //If not, trigger a timer and wait to send the GOAWAY frame
                //If so, call close on the TCP-Channel/Device-Channel below us

                H2StreamProcessor stream;
                for (Integer i : streamTable.keySet()) {
                    stream = streamTable.get(i);

                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "close(vc,e): looking at stream: " + stream.getId());
                    }

                    if (stream.getId() != 0 && !stream.isHalfClosed() && !stream.isStreamClosed() && highestLocalStreamId > -1) {
                        continue;
                    } else {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "close(vc,e): stream not ready to close: " + stream.getId() + " :close: H2InboundLink hc: " + this.hashCode());
                        }
                        return;
                    }
                }
            }

            // All streams are either closed or in half closed, and a GOAWAY frame needs to be sent
            // Wait the timeout time and then send the GOAWAY frame with the last good stream

            linkStatus = LINK_STATUS.WAIT_TO_SEND_GOAWAY;
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "close(vc,e): loading up the wait to close timeout" + " :close: H2InboundLink hc: " + this.hashCode());
            }

            ScheduledExecutorService scheduler = CHFWBundle.getScheduledExecutorService();
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "close : scheduler : " + scheduler + " config : " + config);
            }
            connTimeout = new H2ConnectionTimeout(e);

            if (e == null) {
                // close cleanly if no other traffic has been received for this H2 connection within the timeout
                // Save the future so we can cancel it later on
                closeFuture = scheduler.schedule(connTimeout, config.getH2ConnCloseTimeout(), TimeUnit.SECONDS);
            } else {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "close(vc,e): close on link called with exception: " + e);
                }
                // do the close immediately on this thread
                connTimeout.run();
            }
        }
    }
832209
function RpcChannel(connection) {
    if (!connection) {
        var msg = 'The connection is mandatory!';
        logger.error(msg);
        throw new TypeError(msg);
    }
    this._connection = connection;
    this._open = true;
    this._queue = [];
    var self = this;
    setInterval(function () {
        executor.call(self);
    }, 100).unref();
}
842708
@Nullable Socket releaseConnectionNoEvents() {
    assert (Thread.holdsLock(connectionPool));

    int index = -1;
    for (int i = 0, size = this.connection.transmitters.size(); i < size; i++) {
      Reference<Transmitter> reference = this.connection.transmitters.get(i);
      if (reference.get() == this) {
        index = i;
        break;
      }
    }

    if (index == -1) throw new IllegalStateException();

    RealConnection released = this.connection;
    released.transmitters.remove(index);
    this.connection = null;

    if (released.transmitters.isEmpty()) {
      released.idleAtNanos = System.nanoTime();
      if (connectionPool.connectionBecameIdle(released)) {
        return released.socket();
      }
    }

    return null;
  }
473012
public void connectionFreed(IManagedConnectionEvent<C> event) {
        IPhynixxManagedConnection<C> proxy = event.getManagedConnection();
        if (!proxy.hasCoreConnection()) {
            return;
        } else {
            this.freeConnection(proxy);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Proxy " + proxy + " released");
        }

    }