<commit_before>/*
 *  Copyright 2004-2006 <NAME>
 *
 *  Licensed 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.asteriskjava.live.internal;

import org.asteriskjava.live.ManagerCommunicationException;
import org.asteriskjava.live.MeetMeRoom;
import org.asteriskjava.manager.action.CommandAction;
import org.asteriskjava.manager.event.AbstractMeetMeEvent;
import org.asteriskjava.manager.event.MeetMeLeaveEvent;
import org.asteriskjava.manager.event.MeetMeMuteEvent;
import org.asteriskjava.manager.event.MeetMeTalkingEvent;
import org.asteriskjava.manager.response.CommandResponse;
import org.asteriskjava.manager.response.ManagerError;
import org.asteriskjava.manager.response.ManagerResponse;
import org.asteriskjava.util.DateUtil;
import org.asteriskjava.util.Log;
import org.asteriskjava.util.LogFactory;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Manages MeetMe events on behalf of an AsteriskServer.
 *
 * @author srt
 */
class MeetMeManager
{
    private static final String MEETME_LIST_COMMAND = "meetme list";
    private static final Pattern MEETME_LIST_PATTERN = Pattern.compile("^User #: ([0-9]+).*Channel: (\\S+).*$");

    private final Log logger = LogFactory.getLog(getClass());
    private final AsteriskServerImpl server;
    private final ChannelManager channelManager;

    /**
     * Maps room number to MeetMe room.
     */
    private final Map<String, MeetMeRoomImpl> rooms;

    MeetMeManager(AsteriskServerImpl server, ChannelManager channelManager)
    {
        this.server = server;
        this.channelManager = channelManager;
        this.rooms = new HashMap<String, MeetMeRoomImpl>();
    }

    void initialize()
    {
        synchronized (rooms)
        {
            for (MeetMeRoomImpl room : rooms.values())
            {
                populateRoom(room);
            }
        }
    }

    void disconnected()
    {
        /*
        synchronized (rooms)
        {
            rooms.clear();
        }
        */
    }

    Collection<MeetMeRoom> getMeetMeRooms()
    {
        final Collection<MeetMeRoom> result;

        result = new ArrayList<MeetMeRoom>();
        synchronized (rooms)
        {
            for (MeetMeRoom room : rooms.values())
            {
                if (!room.isEmpty())
                {
                    result.add(room);
                }
            }
        }
        return result;
    }

    void handleMeetMeEvent(AbstractMeetMeEvent event)
    {
        String roomNumber;
        Integer userNumber;
        AsteriskChannelImpl channel;
        MeetMeRoomImpl room;
        MeetMeUserImpl user;

        roomNumber = event.getMeetMe();
        if (roomNumber == null)
        {
            logger.warn("RoomNumber (meetMe property) is null. Ignoring " + event.getClass().getName());
            return;
        }

        userNumber = event.getUserNum();
        if (userNumber == null)
        {
            logger.warn("UserNumber (userNum property) is null. Ignoring " + event.getClass().getName());
            return;
        }

        user = getOrCreateUserImpl(event);
        if (user == null)
        {
            return;
        }

        channel = user.getChannel();
        room = user.getRoom();

        if (event instanceof MeetMeLeaveEvent)
        {
            logger.info("Removing channel " + channel.getName() + " from room " + roomNumber);
            if (room != user.getRoom())
            {
                if (user.getRoom() != null)
                {
                    logger.error("Channel " + channel.getName() + " should be removed from room " + roomNumber
                            + " but is user of room " + user.getRoom().getRoomNumber());
                    user.getRoom().removeUser(user);
                }
                else
                {
                    logger.error("Channel " + channel.getName() + " should be removed from room " + roomNumber
                            + " but is user of no room");
                }
            }
            // Mmmm should remove from the room before firing PropertyChangeEvents ?
            user.left(event.getDateReceived());
            room.removeUser(user);
            channel.setMeetMeUserImpl(null);
        }
        else if (event instanceof MeetMeTalkingEvent)
        {
            Boolean status;

            status = ((MeetMeTalkingEvent) event).getStatus();
            if (status != null)
            {
                user.setTalking(status);
            }
            else
            {
                user.setTalking(true);
            }
        }
        else if (event instanceof MeetMeMuteEvent)
        {
            Boolean status;

            status = ((MeetMeMuteEvent) event).getStatus();
            if (status != null)
            {
                user.setMuted(status);
            }
        }
    }

    private void populateRoom(MeetMeRoomImpl room)
    {
        final CommandAction meetMeListAction;
        final ManagerResponse response;
        final List<String> lines;
        final Collection<Integer> userNumbers = new ArrayList<Integer>(); // list of user numbers in the room

        meetMeListAction = new CommandAction(MEETME_LIST_COMMAND + " " + room.getRoomNumber());
        try
        {
            response = server.sendAction(meetMeListAction);
        }
        catch (ManagerCommunicationException e)
        {
            logger.error("Unable to send \"" + MEETME_LIST_COMMAND + "\" command", e);
            return;
        }
        if (response instanceof ManagerError)
        {
            logger.error("Unable to send \"" + MEETME_LIST_COMMAND + "\" command: " + response.getMessage());
            return;
        }
        if (!(response instanceof CommandResponse))
        {
            logger.error("Response to \"" + MEETME_LIST_COMMAND + "\" command is not a CommandResponse but "
                    + response.getClass());
            return;
        }

        lines = ((CommandResponse) response).getResult();
        for (String line : lines)
        {
            final Matcher matcher;
            final Integer userNumber;
            final AsteriskChannelImpl channel;
            boolean muted = false;
            boolean talking = false;
            MeetMeUserImpl channelUser;
            MeetMeUserImpl roomUser;

            matcher = MEETME_LIST_PATTERN.matcher(line);
            if (!matcher.matches())
            {
                continue;
            }

            userNumber = Integer.valueOf(matcher.group(1));
            channel = channelManager.getChannelImplByName(matcher.group(2));

            userNumbers.add(userNumber);

            if (line.contains("(Admin Muted)") || line.contains("(Muted)"))
            {
                muted = true;
            }

            if (line.contains("(talking)"))
            {
                talking = true;
            }

            channelUser = channel.getMeetMeUser();
            if (channelUser != null && channelUser.getRoom() != room)
            {
                channelUser.left(DateUtil.getDate());
                channelUser = null;
            }
<commit_msg>Prevent null pointer in MeetMeManager<commit_after>/*
 *  Copyright 2004-2006 <NAME>
 *
 *  Licensed 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.asteriskjava.live.internal;

import org.asteriskjava.live.ManagerCommunicationException;
import org.asteriskjava.live.MeetMeRoom;
import org.asteriskjava.manager.action.CommandAction;
import org.asteriskjava.manager.event.AbstractMeetMeEvent;
import org.asteriskjava.manager.event.MeetMeLeaveEvent;
import org.asteriskjava.manager.event.MeetMeMuteEvent;
import org.asteriskjava.manager.event.MeetMeTalkingEvent;
import org.asteriskjava.manager.response.CommandResponse;
import org.asteriskjava.manager.response.ManagerError;
import org.asteriskjava.manager.response.ManagerResponse;
import org.asteriskjava.util.DateUtil;
import org.asteriskjava.util.Log;
import org.asteriskjava.util.LogFactory;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Manages MeetMe events on behalf of an AsteriskServer.
 *
 * @author srt
 */
class MeetMeManager
{
    private static final String MEETME_LIST_COMMAND = "meetme list";
    private static final Pattern MEETME_LIST_PATTERN = Pattern.compile("^User #: ([0-9]+).*Channel: (\\S+).*$");

    private final Log logger = LogFactory.getLog(getClass());
    private final AsteriskServerImpl server;
    private final ChannelManager channelManager;

    /**
     * Maps room number to MeetMe room.
     */
    private final Map<String, MeetMeRoomImpl> rooms;

    MeetMeManager(AsteriskServerImpl server, ChannelManager channelManager)
    {
        this.server = server;
        this.channelManager = channelManager;
        this.rooms = new HashMap<String, MeetMeRoomImpl>();
    }

    void initialize()
    {
        synchronized (rooms)
        {
            for (MeetMeRoomImpl room : rooms.values())
            {
                populateRoom(room);
            }
        }
    }

    void disconnected()
    {
        /*
        synchronized (rooms)
        {
            rooms.clear();
        }
        */
    }

    Collection<MeetMeRoom> getMeetMeRooms()
    {
        final Collection<MeetMeRoom> result;

        result = new ArrayList<MeetMeRoom>();
        synchronized (rooms)
        {
            for (MeetMeRoom room : rooms.values())
            {
                if (!room.isEmpty())
                {
                    result.add(room);
                }
            }
        }
        return result;
    }

    void handleMeetMeEvent(AbstractMeetMeEvent event)
    {
        String roomNumber;
        Integer userNumber;
        AsteriskChannelImpl channel;
        MeetMeRoomImpl room;
        MeetMeUserImpl user;

        roomNumber = event.getMeetMe();
        if (roomNumber == null)
        {
            logger.warn("RoomNumber (meetMe property) is null. Ignoring " + event.getClass().getName());
            return;
        }

        userNumber = event.getUserNum();
        if (userNumber == null)
        {
            logger.warn("UserNumber (userNum property) is null. Ignoring " + event.getClass().getName());
            return;
        }

        user = getOrCreateUserImpl(event);
        if (user == null)
        {
            return;
        }

        channel = user.getChannel();
        room = user.getRoom();

        if (event instanceof MeetMeLeaveEvent)
        {
            logger.info("Removing channel " + channel.getName() + " from room " + roomNumber);
            if (room != user.getRoom())
            {
                if (user.getRoom() != null)
                {
                    logger.error("Channel " + channel.getName() + " should be removed from room " + roomNumber
                            + " but is user of room " + user.getRoom().getRoomNumber());
                    user.getRoom().removeUser(user);
                }
                else
                {
                    logger.error("Channel " + channel.getName() + " should be removed from room " + roomNumber
                            + " but is user of no room");
                }
            }
            // Mmmm should remove from the room before firing PropertyChangeEvents ?
            user.left(event.getDateReceived());
            room.removeUser(user);
            channel.setMeetMeUserImpl(null);
        }
        else if (event instanceof MeetMeTalkingEvent)
        {
            Boolean status;

            status = ((MeetMeTalkingEvent) event).getStatus();
            if (status != null)
            {
                user.setTalking(status);
            }
            else
            {
                user.setTalking(true);
            }
        }
        else if (event instanceof MeetMeMuteEvent)
        {
            Boolean status;

            status = ((MeetMeMuteEvent) event).getStatus();
            if (status != null)
            {
                user.setMuted(status);
            }
        }
    }

    private void populateRoom(MeetMeRoomImpl room)
    {
        final CommandAction meetMeListAction;
        final ManagerResponse response;
        final List<String> lines;
        final Collection<Integer> userNumbers = new ArrayList<Integer>(); // list of user numbers in the room

        meetMeListAction = new CommandAction(MEETME_LIST_COMMAND + " " + room.getRoomNumber());
        try
        {
            response = server.sendAction(meetMeListAction);
        }
        catch (ManagerCommunicationException e)
        {
            logger.error("Unable to send \"" + MEETME_LIST_COMMAND + "\" command", e);
            return;
        }
        if (response instanceof ManagerError)
        {
            logger.error("Unable to send \"" + MEETME_LIST_COMMAND + "\" command: " + response.getMessage());
            return;
        }
        if (!(response instanceof CommandResponse))
        {
            logger.error("Response to \"" + MEETME_LIST_COMMAND + "\" command is not a CommandResponse but "
                    + response.getClass());
            return;
        }

        lines = ((CommandResponse) response).getResult();
        for (String line : lines)
        {
            final Matcher matcher;
            final Integer userNumber;
            final AsteriskChannelImpl channel;
            boolean muted = false;
            boolean talking = false;
            MeetMeUserImpl channelUser;
            MeetMeUserImpl roomUser;

            matcher = MEETME_LIST_PATTERN.matcher(line);
            if (!matcher.matches())
            {
                continue;
            }

            userNumber = Integer.valueOf(matcher.group(1));
            channel = channelManager.getChannelImplByName(matcher.group(2));
			if(channel == null)	// User has left the room already in the meanwhile
			{
				continue;
			}

            userNumbers.add(userNumber);

            if (line.contains("(Admin Muted)") || line.contains("(Muted)"))
            {
                muted = true;
            }

            if (line.contains("(talking)"))
            {
                talking = true;
            }

            channelUser = channel.getMeetMeUser();
            if (channelUser != null && channelUser.getRoom() != room)
            {
                channelUser.left(DateUtil.getDate());
                channelUser = null;
            }

{'fraction_non_alphanumeric': 0.09723478485592454, 'fraction_numerical': 0.002067450575009691, 'mean_word_length': 1.831869740212221, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6815562', 'n_tokens_mistral': 4127, 'n_tokens_neox': 3968, 'n_words': 962}