<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.cloudstack.framework.messagebus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.cloudstack.framework.serializer.MessageSerializer;

public class MessageBusBase implements MessageBus {

    private final Gate _gate;
    private final List<ActionRecord> _pendingActions;

    private final SubscriptionNode _subscriberRoot;
    private MessageSerializer _messageSerializer;

    public MessageBusBase() {
        _gate = new Gate();
        _pendingActions = new ArrayList<ActionRecord>();

        _subscriberRoot = new SubscriptionNode(null, "/", null);
    }

    @Override
    public void setMessageSerializer(MessageSerializer messageSerializer) {
        _messageSerializer = messageSerializer;
    }

    @Override
    public MessageSerializer getMessageSerializer() {
        return _messageSerializer;
    }

    @Override
    public void subscribe(String subject, MessageSubscriber subscriber) {
        assert (subject != null);
        assert (subscriber != null);
        if (_gate.enter()) {
            SubscriptionNode current = locate(subject, null, true);
            assert (current != null);
            current.addSubscriber(subscriber);
            _gate.leave();
        } else {
            synchronized (_pendingActions) {
                _pendingActions.add(new ActionRecord(ActionType.Subscribe, subject, subscriber));
            }
        }
    }

    @Override
    public void unsubscribe(String subject, MessageSubscriber subscriber) {
        if (_gate.enter()) {
            if (subject != null) {
                SubscriptionNode current = locate(subject, null, false);
                if (current != null)
                    current.removeSubscriber(subscriber, false);
            } else {
                _subscriberRoot.removeSubscriber(subscriber, true);
            }
            _gate.leave();
        } else {
            synchronized (_pendingActions) {
                _pendingActions.add(new ActionRecord(ActionType.Unsubscribe, subject, subscriber));
            }
        }
    }

    @Override
    public void clearAll() {
        if (_gate.enter()) {
            _subscriberRoot.clearAll();
            doPrune();
            _gate.leave();
        } else {
            synchronized (_pendingActions) {
                _pendingActions.add(new ActionRecord(ActionType.ClearAll, null, null));
            }
        }
    }

    @Override
    public void prune() {
        if (_gate.enter()) {
            doPrune();
            _gate.leave();
        } else {
            synchronized (_pendingActions) {
                _pendingActions.add(new ActionRecord(ActionType.Prune, null, null));
            }
        }
    }

    private void doPrune() {
        List<SubscriptionNode> trimNodes = new ArrayList<SubscriptionNode>();
        _subscriberRoot.prune(trimNodes);

        while (trimNodes.size() > 0) {
            SubscriptionNode node = trimNodes.remove(0);
            SubscriptionNode parent = node.getParent();
            if (parent != null) {
                parent.removeChild(node.getNodeKey());
                if (parent.isTrimmable()) {
                    trimNodes.add(parent);
                }
            }
        }
    }

    @Override
    public void publish(String senderAddress, String subject, PublishScope scope, Object args) {

        if (_gate.enter(true)) {

            List<SubscriptionNode> chainFromTop = new ArrayList<SubscriptionNode>();
            SubscriptionNode current = locate(subject, chainFromTop, false);

            if (current != null)
                current.notifySubscribers(senderAddress, subject, args);

            Collections.reverse(chainFromTop);
            for (SubscriptionNode node : chainFromTop)
                node.notifySubscribers(senderAddress, subject, args);

            _gate.leave();
        }
    }

    private void onGateOpen() {
        synchronized (_pendingActions) {
            ActionRecord record = null;
            while (_pendingActions.size() > 0) {
                record = _pendingActions.remove(0);
                switch (record.getType()) {
                    case Subscribe: {
                        SubscriptionNode current = locate(record.getSubject(), null, true);
                        assert (current != null);
                        current.addSubscriber(record.getSubscriber());
                    }
                        break;

                    case Unsubscribe:
                        if (record.getSubject() != null) {
                            SubscriptionNode current = locate(record.getSubject(), null, false);<commit_msg>CLOUDSTACK-6305: protect lock leaking from unhandled exception<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.cloudstack.framework.messagebus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.cloudstack.framework.serializer.MessageSerializer;

public class MessageBusBase implements MessageBus {

    private final Gate _gate;
    private final List<ActionRecord> _pendingActions;

    private final SubscriptionNode _subscriberRoot;
    private MessageSerializer _messageSerializer;

    public MessageBusBase() {
        _gate = new Gate();
        _pendingActions = new ArrayList<ActionRecord>();

        _subscriberRoot = new SubscriptionNode(null, "/", null);
    }

    @Override
    public void setMessageSerializer(MessageSerializer messageSerializer) {
        _messageSerializer = messageSerializer;
    }

    @Override
    public MessageSerializer getMessageSerializer() {
        return _messageSerializer;
    }

    @Override
    public void subscribe(String subject, MessageSubscriber subscriber) {
        assert (subject != null);
        assert (subscriber != null);
        if (_gate.enter()) {
            try {
                SubscriptionNode current = locate(subject, null, true);
                assert (current != null);
                current.addSubscriber(subscriber);
            } finally {
                _gate.leave();
            }
        } else {
            synchronized (_pendingActions) {
                _pendingActions.add(new ActionRecord(ActionType.Subscribe, subject, subscriber));
            }
        }
    }

    @Override
    public void unsubscribe(String subject, MessageSubscriber subscriber) {
        if (_gate.enter()) {
            try {
                if (subject != null) {
                    SubscriptionNode current = locate(subject, null, false);
                    if (current != null)
                        current.removeSubscriber(subscriber, false);
                } else {
                    _subscriberRoot.removeSubscriber(subscriber, true);
                }
            } finally {
                _gate.leave();
            }
        } else {
            synchronized (_pendingActions) {
                _pendingActions.add(new ActionRecord(ActionType.Unsubscribe, subject, subscriber));
            }
        }
    }

    @Override
    public void clearAll() {
        if (_gate.enter()) {
            try {
                _subscriberRoot.clearAll();
                doPrune();
            } finally {
                _gate.leave();
            }
        } else {
            synchronized (_pendingActions) {
                _pendingActions.add(new ActionRecord(ActionType.ClearAll, null, null));
            }
        }
    }

    @Override
    public void prune() {
        if (_gate.enter()) {
            try {
                doPrune();
            } finally {
                _gate.leave();
            }
        } else {
            synchronized (_pendingActions) {
                _pendingActions.add(new ActionRecord(ActionType.Prune, null, null));
            }
        }
    }

    private void doPrune() {
        List<SubscriptionNode> trimNodes = new ArrayList<SubscriptionNode>();
        _subscriberRoot.prune(trimNodes);

        while (trimNodes.size() > 0) {
            SubscriptionNode node = trimNodes.remove(0);
            SubscriptionNode parent = node.getParent();
            if (parent != null) {
                parent.removeChild(node.getNodeKey());
                if (parent.isTrimmable()) {
                    trimNodes.add(parent);
                }
            }
        }
    }

    @Override
    public void publish(String senderAddress, String subject, PublishScope scope, Object args) {

        if (_gate.enter(true)) {
            try {
                List<SubscriptionNode> chainFromTop = new ArrayList<SubscriptionNode>();
                SubscriptionNode current = locate(subject, chainFromTop, false);

                if (current != null)
                    current.notifySubscribers(senderAddress, subject, args);

                Collections.reverse(chainFromTop);
                for (SubscriptionNode node : chainFromTop)
                    node.notifySubscribers(senderAddress, subject, args);
            } finally {
                _gate.leave();
            }
        }
    }

    private void onGateOpen() {
        synchronized (_pendingActions) {
            ActionRecord record = null;
            while (_pendingActions.size() > 0) {
                record = _pendingActions.remove(0);
                switch (record.getType()) {
                    case Subscribe: {
                        SubscriptionNode current = locate(record.getSubject(), null, true);
                        assert (current != null);
                        current.addSubscriber(record.getSubscriber());
                    }
                        break;

                    case Unsubscribe:
                        if (record.getSubject() != null) {
                            SubscriptionNode current = locate(record.getSubject(), null, false);
{'fraction_non_alphanumeric': 0.08756597732975686, 'fraction_numerical': 0.0017305529116552738, 'mean_word_length': 1.9575230296827022, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4826998', 'n_tokens_mistral': 2808, 'n_tokens_neox': 2724, 'n_words': 751}