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.
518449
private boolean mkdirs(FTPClient client, Path file, FsPermission permission)
      throws IOException {
    boolean created = true;
    Path workDir = new Path(client.printWorkingDirectory());
    Path absolute = makeAbsolute(workDir, file);
    String pathName = absolute.getName();
    if (!exists(client, absolute)) {
      Path parent = absolute.getParent();
      created = (parent == null || mkdirs(client, parent, FsPermission
          .getDefault()));
      if (created) {
        String parentDir = parent.toUri().getPath();
        client.changeWorkingDirectory(parentDir);
        created = created & client.makeDirectory(pathName);
      }
    } else if (isFile(client, absolute)) {
      throw new IOException(String.format(
          "Can't make directory for path %s since it is a file.", absolute));
    }
    return created;
  }
267016
private URLConnection openConnection() throws IOException {
		return (null == this.proxy) ? url.openConnection() : url.openConnection(this.proxy);
	}
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);
		}
	}
866808
@Override
    public java.net.Socket createSocket() throws IOException {
        // This is the code to support outbound ssl config for an unconnected socket.
        // To make this code work, the caller side needs to set either sslProperties by using setSSLPropertiesOnThread
        // or outbound connection info with host/port information by using setOutboundConnectionInfo.
        // Either case, the thread attached information needs to be cleared after creating a socket.
        if (tc.isEntryEnabled())
            Tr.entry(tc, "createSocket");
        javax.net.ssl.SSLSocketFactory currentFactory = default_factory;
        javax.net.ssl.SSLSocket socket = null;
        java.util.Properties sslProps = props;
        if (default_constructor) {
            try {
                java.util.Properties sslPropsOnThread = getSSLPropertiesOnThread();
                java.util.Map<String, Object> currentConnectionInfo = JSSEHelper.getInstance().getOutboundConnectionInfo();
                if ((sslPropsOnThread != null) || (currentConnectionInfo != null)) {
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "either SSLProperties on thread or connectionInfo is available.");
                    if (currentConnectionInfo == null) {
                        currentConnectionInfo = new HashMap<String, Object>();
                        currentConnectionInfo.put(Constants.CONNECTION_INFO_DIRECTION, Constants.DIRECTION_OUTBOUND);
                    }
                    sslProps = getProperties(null, currentConnectionInfo, null);
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Getting SSLSocketFactory");
                    currentFactory = getSSLSocketFactory(currentConnectionInfo, sslProps);
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Got SSLSocketFactory", new Object[] { currentFactory });
                } else {
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Neither SSLProperties nor outboundConnectionInfo is set and this is an unconnected socket so create a WSSocket.");
                    java.net.Socket ws_socket = (Socket) AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {

                            return (new com.ibm.ws.ssl.config.WSSocket(new java.net.Socket()));
                        }
                    });
                    if (tc.isEntryEnabled())
                        Tr.exit(tc, "createSocket");
                    return ws_socket;
                }

            } catch (Exception e) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "Exception getting SSLSocketFactory. Fall back to the default SSLSocketFactory", new Object[] { e });
                FFDCFilter.processException(e, getClass().getName(), "createSocket", this);
                currentFactory = default_factory;
            }
        } else {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Use default SSLSocketFactory - the default constructor was not used");
        }
        if (currentFactory != null) {
            socket = (javax.net.ssl.SSLSocket) currentFactory.createSocket();
            socket = SSLConfigManager.getInstance().setCipherListOnSocket(sslProps, socket);
        } else
            throw new javax.net.ssl.SSLException("SSLSocketFactory is null. This can occur if javax.net.ssl.SSLSocketFactory.getDefault() is called to create a socket and javax.net.ssl.* properties are not set.");

        if (tc.isEntryEnabled())
            Tr.exit(tc, "createSocket");
        return socket;
    }
1099779
public boolean isConnectionClose() {
        boolean result = true;
        if (mMalformedHeader) {
            return true;
        }

        if (isHttp10()) {
            // HTTP 1.0 default to close unless keep alive.
            result = true;
            try {
                if (getHeader(CONNECTION).equalsIgnoreCase(_KEEP_ALIVE) || getHeader(PROXY_CONNECTION).equalsIgnoreCase(_KEEP_ALIVE)) {
                    return false;
                }
            } catch (NullPointerException e) {
            }

        } else if (isHttp11()) {
            // HTTP 1.1 default to keep alive unless close.
            result = false;
            try {
                if (getHeader(CONNECTION).equalsIgnoreCase(_CLOSE)) {
                    return true;
                } else if (getHeader(PROXY_CONNECTION).equalsIgnoreCase(_CLOSE)) {
                    return true;
                }
            } catch (NullPointerException e) {
            }
        }
        return result;
    }
452469
def close_connection(self):
        
        if self.port:
            self.port.close()
            self.logger.debug("Close TCP port")
794877
public void returnConnection(DataConnection connection) {
        if (connection.isUsable()) {
            connection.setLastUsage(new Date());
            availableConnections.add(connection);
        }
        else {
            connection.close();
        }

        usedConnections.remove(connection);
    }
811180
private boolean tryOpenAsync() {
        Connection<CL> connection = null;
        // Try to open a new connection, as long as we haven't reached the max
        if (activeCount.get() < config.getMaxConnsPerHost()) {
            try {
                if (activeCount.incrementAndGet() <= config.getMaxConnsPerHost()) {
                    // Don't try to open too many connections at the same time.
                    if (pendingConnections.incrementAndGet() > config.getMaxPendingConnectionsPerHost()) {
                        pendingConnections.decrementAndGet();
                    }
                    else {
                        try {
                            connectAttempt.incrementAndGet();
                            connection = factory.createConnection(this);
                            connection.openAsync(new Connection.AsyncOpenCallback<CL>() {
                                @Override
                                public void success(Connection<CL> connection) {
                                    openConnections.incrementAndGet();
                                    pendingConnections.decrementAndGet();
                                    availableConnections.add(connection);
    
                                    // Sanity check in case the connection
                                    // pool was closed
                                    if (isShutdown()) {
                                        discardIdleConnections();
                                    }
                                }
    
                                @Override
                                public void failure(Connection<CL> conn, ConnectionException e) {
                                    failedOpenConnections.incrementAndGet();
                                    pendingConnections.decrementAndGet();
                                    activeCount.decrementAndGet();
    
                                    if (e instanceof IsDeadConnectionException) {
                                        noteError(e);
                                    }
                                }
                            });
                            return true;
                        }
                        catch (ThrottledException e) {
                            // Trying to open way too many connections here
                        }
                        finally {
                            if (connection == null)
                                pendingConnections.decrementAndGet();
                        }
                    }
                }
            }
            finally {
                if (connection == null) {
                    activeCount.decrementAndGet();
                }
            }
        }
        return false;
    }
7935
private void discardIdleConnections() {
        List<Connection<CL>> connections = Lists.newArrayList();
        availableConnections.drainTo(connections);
        activeCount.addAndGet(-connections.size());

        for (Connection<CL> connection : connections) {
            try {
                closedConnections.incrementAndGet();
                connection.close(); // This is usually an async operation
            }
            catch (Throwable t) {
                // TODO
            }
        }
    }
1041732
void dropNonPreferredConnections()
    {
        final String methodName = "dropNonPreferredConnections";
        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
        {
            SibTr.entry(this, TRACE, methodName);
        }

        // If we are connected to a non preferred then we will NEVER be connect to a preferred as 
        // well, there is no mixing of connection types.
        if (!_connectedToPreferred)
        {
            closeConnections();
        }

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
        {
            SibTr.exit(TRACE, methodName);
        }
    }
1025822
@Override
	public final void closeTcpConnection() throws CommunicationException {
		IOException tmpException = null;
		try {
			closeTcpConnectionImpl();
		} catch (IOException e) {
			tmpException = e;
		} finally {
			try {

				if (mSocket != null) {
					mSocket.close();
				}

			} catch (IOException e) {
				tmpException = e;
			} finally {
				mSocket = null;
			}
		}

		if (tmpException != null) {
			throw new CommunicationException(tmpException);
		}
	}
1330967
@Override
  public StateConnection onCloseRead()
  {
    ConnectionProtocol request = request();
    
    if (request != null) {
      request.onCloseRead();
    }
    
    _sequenceClose.set(_sequenceRead.get());
    
    if (_sequenceFlush.get() < _sequenceClose.get()) {
      _isClosePending.set(true);
      
      if (_sequenceFlush.get() < _sequenceClose.get()) {
        return StateConnection.CLOSE_READ_S;
      }
      else {
        _isClosePending.set(false);
        
        return StateConnection.CLOSE;
      }
    }
    else {
      return StateConnection.CLOSE;
    }
  }
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();
            }
        }
    }
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); 
			}
		}
    }
500097
private Connection getConnection(InetSocketAddress addr,
                                   Class<?> protocol,
                                   UserGroupInformation ticket,
                                   int rpcTimeout,
                                   Call call)
                                   throws IOException {
    if (!running.get()) {
      // the client is stopped
      throw new IOException("The client is stopped");
    }
    Connection connection;
    /* we could avoid this allocation for each RPC by having a  
     * connectionsId object and with set() method. We need to manage the
     * refs for keys in HashMap properly. For now its ok.
     */
    ConnectionId remoteId = new ConnectionId(
		addr, protocol, ticket, rpcTimeout);
    do {
      synchronized (connections) {
        connection = connections.get(remoteId);
        if (connection == null) {
          connection = new Connection(remoteId);
          connections.put(remoteId, connection);
        }
      }
    } while (!connection.addCall(call));
    
    //we don't invoke the method below inside "synchronized (connections)"
    //block above. The reason for that is if the server happens to be slow,
    //it will take longer to establish a connection and that will slow the
    //entire system down.
    boolean success = false;
    try {
      connection.setupIOstreams();
      success = true;
    } finally {
      if (!success) {
        // We need to make sure connection is removed from connections object if
        // there is any unhandled exception (like OOM). In this case, unlikely
        // there is response thread started which can clear the connection
        // eventually.
        try {
          if (connection.closeException == null) {
            connection.markClosed(new IOException(
                "Unexpected error when setup IO Stream"));
          }
        } finally {
          connection.close(true);
        }
      }
    }
    return connection;
  }
205494
protected synchronized void close(OutboundConnection connection)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "close", connection);

        // Paranoia: Check that this connection believes that it belongs in this group.
        if (connection.getConnectionData().getConnectionDataGroup() != this)
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                SibTr.debug(this, tc, "connection does not belong to this group", connection.getConnectionData().getConnectionDataGroup());
            throw new SIErrorException(nls.getFormattedMessage("CONNDATAGROUP_INTERNAL_SICJ0062", null, "CONNDATAGROUP_INTERNAL_SICJ0062")); // D226223
        }

        ConnectionData data;
        boolean isNowIdle = false;

        synchronized (connectionData)
        {
            data = connection.getConnectionData();
            data.decrementUseCount();
            if (data.getUseCount() == 0)
            {
                // If no one is using this connection, then remove it from our group and
                // add it to the idle pool.
                connectionData.remove(data);
                isNowIdle = true;
            }
        }

        if (isNowIdle)
        {
            IdleConnectionPool.getInstance().add(data.getConnection(), groupEndpointDescriptor);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "close");
    }
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");
        }

    }