Get the {@link Buffer} where events are stored when network is down.

@param dsn Dsn passed in by the user.
@return the {@link Buffer} where events are stored when network is down.
162454
protected Buffer getBuffer(Dsn dsn) {
        String bufferDir = Lookup.lookup(BUFFER_DIR_OPTION, dsn);
        if (bufferDir != null) {
            return new DiskBuffer(new File(bufferDir), getBufferSize(dsn));
        }
        return null;
    }
648774
@Override
	public void connectionEvent(Connection conn, Events type) {
		switch (type) {
		case CONNECTED:

			// The connection is permanently closed, either by manual action or
			// failed reconnects
			if (debug) {
				logger.info("NATS connection opened.");
			}
			break;

		case CLOSED:

			// The connection lost its connection, but may try to reconnect if
			// configured to
			logger.info("NATS connection closed.");
			if (started.get()) {
				reconnect();
			}
			break;

		case DISCONNECTED:

			// The connection was connected, lost its connection and
			// successfully reconnected
			if (debug) {
				logger.info("NATS pub-sub connection disconnected.");
			}
			break;

		case RECONNECTED:

			// The connection was reconnected and the server has been notified
			// of all subscriptions
			if (debug) {
				logger.info("NATS connection reconnected.");
			}
			break;

		case RESUBSCRIBED:

			// The connection was told about new servers from, from the current
			// server
			if (debug) {
				logger.info("NATS subscriptions re-established.");
			}
			break;

		case DISCOVERED_SERVERS:

			// Servers discovered
			if (debug) {
				logger.info("NATS servers discovered.");
			}
			break;

		default:
			break;
		}
	}
270552
protected int getTimeout(Dsn dsn) {
        return Util.parseInteger(Lookup.lookup(TIMEOUT_OPTION, dsn), TIMEOUT_DEFAULT);
    }
1165211
protected int getMaxMessageLength(Dsn dsn) {
        return Util.parseInteger(
            Lookup.lookup(MAX_MESSAGE_LENGTH_OPTION, dsn), JsonMarshaller.DEFAULT_MAX_MESSAGE_LENGTH);
    }
539243
public List<Object> decodeBuffer(RTMPConnection conn, IoBuffer buffer) {
        final int position = buffer.position();
        //if (log.isTraceEnabled()) {
            //log.trace("decodeBuffer: {}", Hex.encodeHexString(Arrays.copyOfRange(buffer.array(), position, buffer.limit())));
        //}
        // decoded results
        List<Object> result = null;
        if (conn != null) {
            //log.trace("Decoding for connection - session id: {}", conn.getSessionId());
            try {
                // instance list to hold results
                result = new LinkedList<>();
                // get the local decode state
                RTMPDecodeState state = conn.getDecoderState();
                //if (log.isTraceEnabled()) {
                    //log.trace("RTMP decode state {}", state);
                //}
                if (!conn.getSessionId().equals(state.getSessionId())) {
                    log.warn("Session decode overlap: {} != {}", conn.getSessionId(), state.getSessionId());
                }
                int remaining;
                while ((remaining = buffer.remaining()) > 0) {
                    if (state.canStartDecoding(remaining)) {
                        //log.trace("Can start decoding");
                        state.startDecoding();
                    } else {
                        log.trace("Cannot start decoding");
                        break;
                    }
                    final Object decodedObject = decode(conn, state, buffer);
                    if (state.hasDecodedObject()) {
                        //log.trace("Has decoded object");
                        if (decodedObject != null) {
                            result.add(decodedObject);
                        }
                    } else if (state.canContinueDecoding()) {
                        //log.trace("Can continue decoding");
                        continue;
                    } else {
                        log.trace("Cannot continue decoding");
                        break;
                    }
                }
            } catch (Exception ex) {
                log.warn("Failed to decodeBuffer: pos {}, limit {}, chunk size {}, buffer {}", position, buffer.limit(), conn.getState().getReadChunkSize(), Hex.encodeHexString(Arrays.copyOfRange(buffer.array(), position, buffer.limit())));
                // catch any non-handshake exception in the decoding; close the connection
                log.warn("Closing connection because decoding failed: {}", conn, ex);
                // clear the buffer to eliminate memory leaks when we can't parse protocol
                buffer.clear();
                // close connection because we can't parse data from it
                conn.close();
            } finally {
                //if (log.isTraceEnabled()) {
                    //log.trace("decodeBuffer - post decode input buffer position: {} remaining: {}", buffer.position(), buffer.remaining());
                //}
                buffer.compact();
            }
        } else {
            log.error("Decoding buffer failed, no current connection!?");
        }
        return result;
    }
378815
protected boolean processBufferedMessages(Event event) throws AvpDataException {
    if (listeners.size() == 0) {
      //PCB added logging
      logger.debug("listeners.size() == 0 on connection [{}]", this.getKey());
      try {
        buffer.add(event);
      }
      catch (IllegalStateException e) {
        logger.debug("Got IllegalStateException in processBufferedMessages");
        // FIXME : requires JDK6 : buffer.removeLast();
        Event[] tempBuffer = buffer.toArray(new Event[buffer.size()]);
        buffer.remove(tempBuffer[tempBuffer.length - 1]);
        buffer.add(event);
      }
      //PCB added logging
      logger.debug("processBufferedMessages is returning false");
      return false;
    }
    else {
      logger.debug("processBufferedMessages is returning true on connection [{}] as there are listeners", getKey());
      return true;
    }
  }
908499
protected int handleDatagram (DatagramChannel listener, long when)
    {
        InetSocketAddress source;
        _databuf.clear();
        try {
            source = (InetSocketAddress)listener.receive(_databuf);
        } catch (IOException ioe) {
            log.warning("Failure receiving datagram.", ioe);
            return 0;
        }

        // make sure we actually read a packet
        if (source == null) {
            log.info("Psych! Got READ_READY, but no datagram.");
            return 0;
        }

        // flip the buffer and record the size (which must be at least 14 to contain the connection
        // id, authentication hash, and a class reference)
        int size = _databuf.flip().remaining();
        if (size < 14) {
            log.warning("Received undersized datagram", "source", source, "size", size);
            return 0;
        }

        // the first four bytes are the connection id
        int connectionId = _databuf.getInt();
        Connection conn = _connections.get(connectionId);
        if (conn != null) {
            ((PresentsConnection)conn).handleDatagram(source, listener, _databuf, when);
        } else {
            log.debug("Received datagram for unknown connection", "id", connectionId,
                      "source", source);
        }

        return size;
    }
1048980
public static String getBufferTraceInfo(WsByteBuffer buffer) {
        if (null == buffer) {
            return "null";
        }
        StringBuilder sb = new StringBuilder(64);
        sb.append("hc=").append(buffer.hashCode());
        sb.append(" pos=").append(buffer.position());
        sb.append(" lim=").append(buffer.limit());
        sb.append(" cap=").append(buffer.capacity());
        return sb.toString();
    }
204071
protected Connection createConnection(Dsn dsn) {
        String protocol = dsn.getProtocol();
        Connection connection;

        if (protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https")) {
            logger.debug("Using an {} connection to Sentry.", protocol.toUpperCase());
            connection = createHttpConnection(dsn);
        } else if (protocol.equalsIgnoreCase("out")) {
            logger.debug("Using StdOut to send events.");
            connection = createStdOutConnection(dsn);
        } else if (protocol.equalsIgnoreCase("noop")) {
            logger.debug("Using noop to send events.");
            connection = new NoopConnection();
        } else {
            throw new IllegalStateException("Couldn't create a connection for the protocol '" + protocol + "'");
        }

        BufferedConnection bufferedConnection = null;
        if (getBufferEnabled(dsn)) {
            Buffer eventBuffer = getBuffer(dsn);
            if (eventBuffer != null) {
                long flushtime = getBufferFlushtime(dsn);
                boolean gracefulShutdown = getBufferedConnectionGracefulShutdownEnabled(dsn);
                Long shutdownTimeout = getBufferedConnectionShutdownTimeout(dsn);
                bufferedConnection = new BufferedConnection(connection, eventBuffer, flushtime, gracefulShutdown,
                    shutdownTimeout);
                connection = bufferedConnection;
            }
        }

        // Enable async unless its value is 'false'.
        if (getAsyncEnabled(dsn)) {
            connection = createAsyncConnection(dsn, connection);
        }

        // If buffering is enabled, wrap connection with synchronous disk buffering "connection"
        if (bufferedConnection != null) {
            connection = bufferedConnection.wrapConnectionWithBufferWriter(connection);
        }

        return connection;
    }
14051
public synchronized int get(byte[] dst, int off, int len) {
        if (available == 0) {
            return 0;
        }

        // limit is last index to read + 1
        int limit = idxGet < idxPut ? idxPut : capacity;
        int count = Math.min(limit - idxGet, len);
        System.arraycopy(buffer, idxGet, dst, off, count);
        idxGet += count;

        if (idxGet == capacity) {
            // Array end reached, check if we have more
            int count2 = Math.min(len - count, idxPut);
            if (count2 > 0) {
                System.arraycopy(buffer, 0, dst, off + count, count2);
                idxGet = count2;
                count += count2;
            } else {
                idxGet = 0;
            }
        }
        available -= count;
        return count;
    }
645600
public static function parse_dsn($dsn)
    {
        if (empty($dsn)) {
            return null;
        }

        // Find phptype and dbsyntax
        if (($pos = strpos($dsn, '://')) !== false) {
            $str = substr($dsn, 0, $pos);
            $dsn = substr($dsn, $pos + 3);
        }
        else {
            $str = $dsn;
            $dsn = null;
        }

        // Get phptype and dbsyntax
        // $str => phptype(dbsyntax)
        if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
            $parsed['phptype']  = $arr[1];
            $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
        }
        else {
            $parsed['phptype']  = $str;
            $parsed['dbsyntax'] = $str;
        }

        if (empty($dsn)) {
            return $parsed;
        }

        // Get (if found): username and password
        // $dsn => username:password@protocol+hostspec/database
        if (($at = strrpos($dsn,'@')) !== false) {
            $str = substr($dsn, 0, $at);
            $dsn = substr($dsn, $at + 1);
            if (($pos = strpos($str, ':')) !== false) {
                $parsed['username'] = rawurldecode(substr($str, 0, $pos));
                $parsed['password'] = rawurldecode(substr($str, $pos + 1));
            }
            else {
                $parsed['username'] = rawurldecode($str);
            }
        }

        // Find protocol and hostspec

        // $dsn => proto(proto_opts)/database
        if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
            $proto       = $match[1];
            $proto_opts  = $match[2] ? $match[2] : false;
            $dsn         = $match[3];
        }
        // $dsn => protocol+hostspec/database (old format)
        else {
            if (strpos($dsn, '+') !== false) {
                list($proto, $dsn) = explode('+', $dsn, 2);
            }
            if (   strpos($dsn, '//') === 0
                && strpos($dsn, '/', 2) !== false
                && $parsed['phptype'] == 'oci8'
            ) {
                //oracle's "Easy Connect" syntax:
                //"username/password@[//]host[:port][/service_name]"
                //e.g. "scott/tiger@//mymachine:1521/oracle"
                $proto_opts = $dsn;
                $pos = strrpos($proto_opts, '/');
                $dsn = substr($proto_opts, $pos + 1);
                $proto_opts = substr($proto_opts, 0, $pos);
            }
            else if (strpos($dsn, '/') !== false) {
                list($proto_opts, $dsn) = explode('/', $dsn, 2);
            }
            else {
                $proto_opts = $dsn;
                $dsn = null;
            }
        }

        // process the different protocol options
        $parsed['protocol'] = $proto ?: 'tcp';
        $proto_opts = rawurldecode($proto_opts);
        if (strpos($proto_opts, ':') !== false) {
            list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
        }
        if ($parsed['protocol'] == 'tcp') {
            $parsed['hostspec'] = $proto_opts;
        }
        else if ($parsed['protocol'] == 'unix') {
            $parsed['socket'] = $proto_opts;
        }

        // Get dabase if any
        // $dsn => database
        if ($dsn) {
            // /database
            if (($pos = strpos($dsn, '?')) === false) {
                $parsed['database'] = rawurldecode($dsn);
            // /database?param1=value1&param2=value2
            }
            else {
                $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
                $dsn = substr($dsn, $pos + 1);
                if (strpos($dsn, '&') !== false) {
                    $opts = explode('&', $dsn);
                }
                else { // database?param1=value1
                    $opts = array($dsn);
                }
                foreach ($opts as $opt) {
                    list($key, $value) = explode('=', $opt);
                    if (!array_key_exists($key, $parsed) || false === $parsed[$key]) {
                        // don't allow params overwrite
                        $parsed[$key] = rawurldecode($value);
                    }
                }
            }
        }

        return $parsed;
    }
15270
@SuppressWarnings("unused")
    private String getEventName(byte[] inputs) {
        String  s = new String(inputs);
        //  Remove Tango host
        int pos = s.lastIndexOf('.');
        for (int i=0 ; i<4 ; i++)
            pos = s.lastIndexOf('/', pos-1);
        return s.substring(pos+1);
    }
    //
    //
    private void checkEventMessage(byte[][] inputs) throws Exception {

        if (inputs.length<NbFields) {   // || inputs[EndianIdx].length==0) {
            System.err.println("NbFields=" + NbFields);
            eventDrift = 4 - inputs.length;
            Except.throw_exception("Api_BadParameterException",
                    "Cannot decode event  (message size !)",
                    "ZmqMainThread.checkEventMessage()");
        }
        if (new String(inputs[NameIdx]).startsWith("tango://")) {
            //if (new String(inputs[NameIdx]).toLowerCase().contains("position"))
            //    System.out.println("checkEventMessage(): Receive " +new String(inputs[NameIdx]));
            return; //  OK
        }

        //  Check what is first input ?
        byte[]  bytes = inputs[NameIdx];
        if (bytes.length==1) {
            //  Endianess
            eventDrift = 3;
            Except.throw_exception("Api_BadParameterException",
                    "Cannot decode event  (start with endianess)",
                    "ZmqMainThread.checkEventMessage()");
        }
        else
        if (bytes[0]==0xc && bytes[1]==0x0 && bytes[2]==0xd && bytes[3]==0xe) {
            //  DATA
            eventDrift = 1;
            Except.throw_exception("Api_BadParameterException",
                    "Cannot decode event  (start with data)",
                    "ZmqMainThread.checkEventMessage()");
        }
        else {
            //  Specifications
            eventDrift = 2;
            Except.throw_exception("Api_BadParameterException",
                    "Cannot decode event  (start with specifications)",
                    "ZmqMainThread.checkEventMessage()");
        }
    }
    //
    /**
     * Manage events. Extract data and push to callback
     * @param inputs received messages
     * @throws DevFailed if cannot extract event type or data from messages.
     */
    //
    private void manageEvent(byte[][] inputs) throws DevFailed {

        try {
            //  Check if inputs are coherent
            checkEventMessage(inputs);

            //  Decode receive data parts
            //String  eventName = getEventName(inputs[NameIdx]);
            String  eventName = new String(inputs[NameIdx]);
            boolean littleEndian = true;
            if (inputs[EndianIdx].length>0) {
                //  Sometimes inputs[EndianIdx] could be empty (fixed in c++ 8.1)
                littleEndian = (inputs[EndianIdx][0]!=0);
            }
            ZmqCallInfo zmqCallInfo =
                    ZMQutils.deMarshallZmqCallInfo(inputs[ZmqInfoIdx], littleEndian);
            if (zmqCallInfo!=null) {
                manageEventValue(eventName, ApiUtil.toLongUnsigned(zmqCallInfo.ctr),
                        inputs[ValueIdx], littleEndian, zmqCallInfo.call_is_except);
            }
            else
                throw new Exception("DeMarshalling returns null");
        }
        catch (Exception e) {
            if (e instanceof DevFailed)
                throw (DevFailed) e;
            e.printStackTrace();
            Except.throw_exception("Api_CatchException",
                    "API catch a " + e.toString() + " exception",
                    "ZmqMainThread.manageEvent()");
        }
    }
    //
    //
    private EventCallBackStruct getEventCallBackStruct(String eventName) {
        List<String> possibleTangoHosts = EventConsumer.possibleTangoHosts;
        Hashtable<String, EventCallBackStruct> callbackMap = ZmqEventConsumer.getEventCallbackMap();
        if (callbackMap.containsKey(eventName)) {
            return callbackMap.get(eventName);
        }
        //  Check with other TangoHosts using possibleTangoHosts as header
        int index = eventName.indexOf("//");
        if (index>0) {
            index = eventName.indexOf('/', index+2); //  "//".length()
            for (String possibleTangoHost : possibleTangoHosts) {
                String key = possibleTangoHost + eventName.substring(index);
                if (callbackMap.containsKey(key)) {
                    return callbackMap.get(key);
                }
            }
        }

        //  Not found
        /*  Display table content
		if (eventName.contains("maxtempchange")) {
			System.err.println("");
			System.err.println(eventName + " NOT FOUND");
			System.err.println("keys are:");
        	Enumeration<String> keys = callbackMap.keys();
        	while (keys.hasMoreElements()) {
            	System.err.println(keys.nextElement());
        	}
		}
        */
        return null;
    }
    //
    //
    private void manageEventValue(String eventName,
                                  long eventCounter,
                                  byte[] recData,
                                  boolean littleEndian,
                                  boolean isExcept) throws  DevFailed {
        //System.out.println("Event name  = " + eventName);
        EventCallBackStruct callBackStruct = getEventCallBackStruct(eventName);
        if (callBackStruct!=null) {
            DeviceAttribute attributeValue  = null;
            DevicePipe      devicePipe      = null;
            AttributeInfoEx attributeConfig = null;
            AttDataReady    dataReady       = null;
            DeviceInterface deviceInterface = null;
            DevError[]      devErrorList    = null;

            //  Manage ZMQ counter (queue has reached HWM ?)
            boolean pushTheEvent =
                    manageEventCounter(callBackStruct, eventName, eventCounter);
            ZMQutils.zmqEventTrace("ZMQ event from " + eventName);

            //  Check if Value part is a DevFailed
            if (isExcept) {
                devErrorList = ZMQutils.deMarshallErrorList(recData, littleEndian);
            }
            else {
                Hashtable<String, EventChannelStruct> channelMap = EventConsumer.getChannelMap();
                EventChannelStruct eventChannelStruct = channelMap.get(callBackStruct.channel_name);
                if (eventChannelStruct!=null) {
                    try {
                        //  Needs idl version to de marshall
                        int idl = callBackStruct.device.get_idl_version();

                        //  Else check event type
                        switch (ZMQutils.getEventType(eventName)) {
                            case TangoConst.ATT_CONF_EVENT:
                                attributeConfig =
                                        ZMQutils.deMarshallAttributeConfig(recData, littleEndian, idl);
                                break;
                            case TangoConst.PIPE_EVENT:
                                devicePipe = ZMQutils.deMarshallPipe(recData, littleEndian, idl);
                                break;
                            case TangoConst.DATA_READY_EVENT:
                                dataReady = ZMQutils.deMarshallAttDataReady(recData, littleEndian);
                                break;
                            case TangoConst.INTERFACE_CHANGE:
                                deviceInterface = ZMQutils.deMarshallAttInterfaceChange(recData, littleEndian);
                                break;
                            default:
                                attributeValue = ZMQutils.deMarshallAttribute(recData, littleEndian, idl);
                         }
                    }
                    catch(DevFailed e) {
                        //  convert de marshall
                        devErrorList = e.errors;
                    }
                }
            }
            if (pushTheEvent) {
                //	Build and push event data
                String  deviceName = getDeviceName(eventName);
                pushEventData(callBackStruct,
                        new EventData(callBackStruct.device,
                                deviceName, eventName,
                                callBackStruct.event_type, EventData.ZMQ_EVENT,
                                attributeValue, devicePipe,
                                attributeConfig, dataReady,
                                deviceInterface, devErrorList));
            }
        }
        else
            System.err.println(eventName + " ?  NOT FOUND");
    }
    //
    /**
     * Manage the event counter
     * @param callBackStruct    the event callback structure
     * @param eventName         the event name
     * @param eventCounter    the event counter to manage
     * @return true if the event must be pushed.
     * @throws DevFailed if at least one event has been lost
     */
    //
    private boolean manageEventCounter(EventCallBackStruct callBackStruct,
                                    String eventName,
                                    long eventCounter) throws DevFailed {
        long    previousCounter = callBackStruct.getZmqCounter();
        //  Is it the first call ?
        if (previousCounter==Long.MAX_VALUE) {
            callBackStruct.setZmqCounter(eventCounter);
            //  There is NO synchronous call for DataReady event !!!!
            if (callBackStruct.event_name.equals(
                    TangoConst.eventNames[TangoConst.DATA_READY_EVENT])) {
                callBackStruct.setSynchronousDone(true);
            }
            //  To be sure to have first event after synchronous call,
            //      wait the event pushed in dedicated thread.
            int timeout = 5000;
            for (int i=0 ; !callBackStruct.isSynchronousDone() && i<timeout ; i++) {
                try { Thread.sleep(1); } catch (InterruptedException e) { /* */ }
            }
            return true;
        }

        long    delta = eventCounter - previousCounter;
        //  If delta==0 --> already receive (ZMQ bug)
        if (delta==0) {
            callBackStruct.setZmqCounter(eventCounter);
            return false;
        }
        //  eventCounter<=0  -> reconnection
        if (eventCounter<=0) {
            callBackStruct.setZmqCounter(eventCounter);
            return false;
        }

        //  If delta==1 -> It is OK nothing lost
        if (delta==1) {
            callBackStruct.setZmqCounter(eventCounter);
            return true;
        }

        //  if delta<0  --> integer overflow
        if (delta<0) {
            long    maxCounter = ApiUtil.toLongUnsigned(-1);
            long    delta2 = maxCounter - delta;
            //  If delta2==1 -> It is OK nothing lost
            if (delta2==1) {
                callBackStruct.setZmqCounter(eventCounter);
                return true;
            }
        }
        //  Else
        //  At least one event has been lost, push a DevError event
        long nb = eventCounter - (previousCounter+1);
        DevError[]      devErrorList    = new DevError[] {
                    new DevError("Api_MissedEvents", ErrSeverity.ERR,
                        "Missed " + nb + " events ("  +
                                eventCounter + "-" + (previousCounter+1) +
                                ") ! ZMQ queue has reached HWM or resynchronize ?",
                        "ZmqMainThread.manageEventCounter()") };

        //	Build and push event data
        String  deviceName = getDeviceName(eventName);
        pushEventData(callBackStruct,
                new EventData(callBackStruct.device,
                        deviceName, eventName,
                        callBackStruct.event_type, EventData.ZMQ_EVENT,
                        null, null, null, null, null, devErrorList));
        callBackStruct.setZmqCounter(eventCounter);
        return true;
    }
    //
    //
    private void pushEventData(EventCallBackStruct callBackStruct, EventData eventData) {

        if (callBackStruct.use_ev_queue) {
            EventQueue ev_queue = callBackStruct.device.getEventQueue();
            ev_queue.insert_event(eventData);
        } else if (callBackStruct.callback != null) {
            callBackStruct.callback.push_event(eventData);
        }
    }
    //
    /**
     * Manage heartbeat
     * @param inputs received messages
     * @throws DevFailed if cannot get ZmqEventConsumer instance
     */
    //
    private void manageHeartbeat(byte[][] inputs) throws DevFailed{
        //  First part is heartbeat name
        String  name = new String(inputs[NameIdx]);
        //System.out.println("heartbeat : " + name);

        //  Check if name is coherent
        int start = name.indexOf("dserver/");
        if (start<0) {
            //  ToDo
            long    t = System.currentTimeMillis();
            System.err.println(formatTime(t) + ":\n heartbeat: " + name +
                    " cannot be parsed ! length=" + inputs[NameIdx].length);
            ZMQutils.dump(inputs[NameIdx]);

            //  Check if endianess or specif
            if (inputs[NameIdx].length==1)  //  Endianess
                heartbeatDrift = 2;
            else
                heartbeatDrift = 1;
            return;
        }

        //  Get only device name (without event type.
        int end   = name.lastIndexOf('.');
        name = name.substring(0, end);
        //System.out.println("-----------> Receive Heartbeat for " + name);
        ZmqEventConsumer.getInstance().push_structured_event_heartbeat(name);

        //  Second one is endianess
        if (inputs[EndianIdx].length==0) {
            System.err.println("heartbeat "+ name + ":   endianess is missing !!!");
        }
        /*
        else {
             NOT USED
        }
        */
    }
250628
private ByteBuffer getBuffer() throws IOException {
        ByteBuffer buffer;

        // Get the oldest block that has a buffer
        int bufferCount = 0;
        TableBlock takeFromBlock = null;
        for (TableBlock block : _blocks) {
            if (block.hasBuffer()) {
                bufferCount++;
                if (takeFromBlock == null || block.getMostRecentUse() < takeFromBlock.getMostRecentUse()) {
                    takeFromBlock = block;
                }
            }
        }
        if (bufferCount < _bufferCount || takeFromBlock == null) {
            // We haven't used the maximum number of buffers yet, so allocate a new one
            _log.debug("Allocating new block of size {}", _blockSize);
            buffer = ByteBuffer.allocate(_blockSize);
        } else {
            buffer = takeFromBlock.flushAndReleaseBuffer();
            // Reset the buffer for reuse
            buffer.position(0);
            buffer.limit(_blockSize);
        }

        return buffer;
    }
493599
public static String getConnectionEventString(int eventID) {
        switch (eventID) {

            case ConnectionEvent.CONNECTION_CLOSED: 
                return "CONNECTION CLOSED (" + eventID + ')'; 

            case ConnectionEvent.LOCAL_TRANSACTION_STARTED: 
                return "LOCAL TRANSACTION STARTED (" + eventID + ')'; 

            case ConnectionEvent.LOCAL_TRANSACTION_COMMITTED: 
                return "LOCAL TRANSACTION COMMITTED (" + eventID + ')'; 

            case ConnectionEvent.LOCAL_TRANSACTION_ROLLEDBACK: 
                return "LOCAL TRANSACTION ROLLEDBACK (" + eventID + ')'; 

            case ConnectionEvent.CONNECTION_ERROR_OCCURRED: 
                return "CONNECTION ERROR OCCURRED (" + eventID + ')'; 

            case WSConnectionEvent.CONNECTION_ERROR_OCCURRED_NO_EVENT:
                return "CONNECTION ERROR OCCURRED NO EVENT (" + eventID + ')';

            case WSConnectionEvent.SINGLE_CONNECTION_ERROR_OCCURRED:
                return "SINGLE CONNECTION ERROR OCCURRED (" + eventID + ')';
        }

        return "UNKNOWN CONNECTION EVENT CONSTANT (" + eventID + ')'; 
    }
313
public static function fromDSN($dsn)
    {
        $connParams = parse_url($dsn);
        $schemeInfo = explode('+', $connParams['scheme']);
        $modifier = null;
        $scheme = $schemeInfo[0];
        $dbName = isset($connParams['path']) ? substr($connParams['path'], 1) : null;

        if (isset($schemeInfo[1])) {
            $modifier = strtolower($schemeInfo[0]);
            $scheme = $schemeInfo[1];
        }

        if ($scheme != 'influxdb') {
            throw new ClientException($scheme . ' is not a valid scheme');
        }

        if (!in_array($modifier, ['udp'])) {
            throw new ClientException(sprintf("%s modifier specified in DSN is not supported", $modifier));
        }

        $driver = null;
        // set the UDP driver when the DSN specifies UDP
        if ($modifier == 'udp') {
            $driver = new UDP($connParams['host'], $connParams['port']);
        }

        $client = new self($driver);
        return ($dbName ? $client->selectDB($dbName) : $client);
    }
899593
protected RejectedExecutionHandler getRejectedExecutionHandler(Dsn dsn) {
        String overflowName = ASYNC_QUEUE_OVERFLOW_DEFAULT;
        String asyncQueueOverflowOption = Lookup.lookup(ASYNC_QUEUE_OVERFLOW_OPTION, dsn);
        if (!Util.isNullOrEmpty(asyncQueueOverflowOption)) {
            overflowName = asyncQueueOverflowOption.toLowerCase();
        }

        RejectedExecutionHandler handler = REJECT_EXECUTION_HANDLERS.get(overflowName);
        if (handler == null) {
            String options = Arrays.toString(REJECT_EXECUTION_HANDLERS.keySet().toArray());
            throw new RuntimeException("RejectedExecutionHandler not found: '" + overflowName
                + "', valid choices are: " + options);
        }

        return handler;
    }
56898
public static ByteBuffer getDirectByteBuffer(DirectBuffer directBuffer) {
        return directBuffer.byteBuffer() == null
                        ? ByteBuffer.allocateDirect(directBuffer.capacity()).put(directBuffer.byteArray())
                        : directBuffer.byteBuffer();
    }