001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.jmx;
018
019import javax.management.ObjectName;
020
021import com.lmax.disruptor.RingBuffer;
022
023/**
024 * Instruments an LMAX Disruptor ring buffer.
025 */
026public class RingBufferAdmin implements RingBufferAdminMBean {
027
028    private final RingBuffer<?> ringBuffer;
029    private final ObjectName objectName;
030
031    public static RingBufferAdmin forAsyncLogger(final RingBuffer<?> ringBuffer, final String contextName) {
032        final String ctxName = Server.escape(contextName);
033        final String name = String.format(PATTERN_ASYNC_LOGGER, ctxName);
034        return new RingBufferAdmin(ringBuffer, name);
035    }
036
037    public static RingBufferAdmin forAsyncLoggerConfig(final RingBuffer<?> ringBuffer,
038            final String contextName, final String configName) {
039        final String ctxName = Server.escape(contextName);
040        final String cfgName = Server.escape(configName);
041        final String name = String.format(PATTERN_ASYNC_LOGGER_CONFIG, ctxName, cfgName);
042        return new RingBufferAdmin(ringBuffer, name);
043    }
044
045    protected RingBufferAdmin(final RingBuffer<?> ringBuffer, final String mbeanName) {
046        this.ringBuffer = ringBuffer;
047        try {
048            objectName = new ObjectName(mbeanName);
049        } catch (final Exception e) {
050            throw new IllegalStateException(e);
051        }
052    }
053
054    @Override
055    public long getBufferSize() {
056        return ringBuffer == null ? 0 : ringBuffer.getBufferSize();
057    }
058
059    @Override
060    public long getRemainingCapacity() {
061        return ringBuffer == null ? 0 : ringBuffer.remainingCapacity();
062    }
063
064    /**
065     * Returns the {@code ObjectName} of this mbean.
066     *
067     * @return the {@code ObjectName}
068     * @see RingBufferAdminMBean#PATTERN_ASYNC_LOGGER
069     * @see RingBufferAdminMBean#PATTERN_ASYNC_LOGGER_CONFIG
070     */
071    public ObjectName getObjectName() {
072        return objectName;
073    }
074
075}