    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     */
    017    package org.apache.logging.log4j.core.appender;
    018
    019    import java.util.HashMap;
    020    import java.util.Map;
    021    import java.util.concurrent.locks.Lock;
    022    import java.util.concurrent.locks.ReentrantLock;
    023
    024    import org.apache.logging.log4j.Logger;
    025    import org.apache.logging.log4j.status.StatusLogger;
    026
    027    /**
    028     * Abstract base class used to register managers.
    029     */
    030    public abstract class AbstractManager {
    031
    032        /**
    033         * Allow subclasses access to the status logger without creating another instance.
    034         */
    035        protected static final Logger LOGGER = StatusLogger.getLogger();
    036
    037        // Need to lock that map instead of using a ConcurrentMap due to stop removing the
    038        // manager from the map and closing the stream, requiring the whole stop method to be locked.
    039        private static final Map<String, AbstractManager> MAP = new HashMap<String, AbstractManager>();
    040
    041        private static final Lock LOCK = new ReentrantLock();
    042
    043        /**
    044         * Number of Appenders using this manager.
    045         */
    046        protected int count;
    047
    048        private final String name;
    049
    050        protected AbstractManager(final String name) {
    051            this.name = name;
    052            LOGGER.debug("Starting {} {}", this.getClass().getSimpleName(), name);
    053        }
    054
    055        /**
    056         * Retrieves a Manager if it has been previously created or creates a new Manager.
    057         * @param name The name of the Manager to retrieve.
    058         * @param factory The Factory to use to create the Manager.
    059         * @param data An Object that should be passed to the factory when creating the Manager.
    060         * @param <M> The Type of the Manager to be created.
    061         * @param <T> The type of the Factory data.
    062         * @return A Manager with the specified name and type.
    063         */
    064        public static <M extends AbstractManager, T> M getManager(final String name, final ManagerFactory<M, T> factory,
    065                                                                  final T data) {
    066            LOCK.lock();
    067            try {
    068                @SuppressWarnings("unchecked")
    069                M manager = (M) MAP.get(name);
    070                if (manager == null) {
    071                    manager = factory.createManager(name, data);
    072                    if (manager == null) {
    073                        throw new IllegalStateException("Unable to create a manager");
    074                    }
    075                    MAP.put(name, manager);
    076                }
    077                manager.count++;
    078                return manager;
    079            } finally {
    080                LOCK.unlock();
    081            }
    082        }
    083
    084        /**
    085         * Determines if a Manager with the specified name exists.
    086         * @param name The name of the Manager.
    087         * @return True if the Manager exists, false otherwise.
    088         */
    089        public static boolean hasManager(final String name) {
    090            LOCK.lock();
    091            try {
    092                return MAP.containsKey(name);
    093            } finally {
    094                LOCK.unlock();
    095            }
    096        }
    097
    098        /**
    099         * May be overridden by Managers to perform processing while the Manager is being released and the
    100         * lock is held.
    101         */
    102        protected void releaseSub() {
    103        }
    104
    105        protected int getCount() {
    106            return count;
    107        }
    108
    109        /**
    110         * Called to signify that this Manager is no longer required by an Appender.
    111         */
    112        public void release() {
    113            LOCK.lock();
    114            try {
    115                --count;
    116                if (count <= 0) {
    117                    MAP.remove(name);
    118                    LOGGER.debug("Shutting down {} {}", this.getClass().getSimpleName(), getName());
    119                    releaseSub();
    120                }
    121            } finally {
    122                LOCK.unlock();
    123            }
    124        }
    125
    126        /**
    127         * Returns the name of the Manager.
    128         * @return The name of the Manager.
    129         */
    130        public String getName() {
    131            return name;
    132        }
    133
    134        /**
    135         * Provide a description of the content format supported by this Manager.  Default implementation returns an empty
    136         * (unspecified) Map.
    137         *
    138         * @return a Map of key/value pairs describing the Manager-specific content format, or an empty Map if no content
    139         * format descriptors are specified.
    140         */
    141        public Map<String, String> getContentFormat() {
    142            return new HashMap<String, String>();
    143        }
    144    }