You are on page 1of 17

ManagerResponse loginResponse; QueueAddAction loginAction = new QueueAddAction(); loginAction.setMemberName("Bob"); loginAction.setQueue("8889"); loginAction.setInterface("Agent/205"); loginAction.setPaused(false); loginResponse = managerConnection.sendAction(loginAction, 0); System.out.

println("Login Response:" + loginResponse.getResponse()); System.out.println("Login Message:" + loginResponse.getMessage()); but then when I run the command: freepbx*CLI> agent show 205 (Bob) not logged in (musiconhold is 'default') 1 agents configured [0 online , 1 offline]

package org.asteriskjava.live; import java.util.Collection; import java.util.Map; import java.util.List; import org.asteriskjava.config.ConfigFile; import org.asteriskjava.live.internal.AsteriskServerImpl; import org.asteriskjava.manager.ManagerConnection; import org.asteriskjava.manager.event.DbGetResponseEvent; import org.asteriskjava.manager.event.PeerEntryEvent; import org.asteriskjava.manager.internal.ManagerConnectionImpl; import org.asteriskjava.manager.response.ManagerResponse; /** * A service-oriented implementation of the AsteriskServer interface. * * @see org.asteriskjava.live.AsteriskServer * @author gmi */ public class BackgroundAsteriskServer implements AsteriskServer { private final AsteriskServerImpl impl;

private boolean started = false; private String hostname = "localhost"; private int port = 5038; private String username = "asterisk"; private String password = "asterisk"; private boolean ssl = false; private int socketTimeout = 5000; private int socketReadTimeout = 60000;

private FirstInitializationThread initThread = null; public BackgroundAsteriskServer() { impl = new AsteriskServerImpl(); /* * Must be called in constructor to guarantee that an addListener() * call won't start the server automatically (in Spring there is no * guaranteed setters call order I think). */ impl.setAutoInitializable(false); } /* * Setters. Should be called before start() if needed. */ public void setHostname(String hostname) { this.hostname = hostname; }

public void setPort(int port) { this.port = port; }

public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; }

public void setSsl(boolean ssl) { this.ssl = ssl; } public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } public void setSocketReadTimeout(int socketReadTimeout) { this.socketReadTimeout = socketReadTimeout; } public void setSkipQueues(boolean skipQueues) { impl.setSkipQueues(skipQueues); } public void setManagerConnection(ManagerConnection eventConnection) { throw new UnsupportedOperationException("You are not supposed to set the eventConnection yourself on this implementation"); } public void initialize() throws ManagerCommunicationException { throw new UnsupportedOperationException("You are not supposed to call initialize yourself on this implementation"); } /* Implementation of the AsteriskServer interface */ public ManagerConnection getManagerConnection() { return impl.getManagerConnection(); } public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout) throws ManagerCommunicationException, NoSuchChannelException { return impl.originateToExtension(channel, context, exten, priority, timeout); } public AsteriskChannel originateToExtension(String channel, String context,

String exten, int priority, long timeout, CallerId callerId, Map<String, String> variables) throws ManagerCommunicationException, NoSuchChannelException { return impl.originateToExtension(channel, context, exten, priority, timeout, callerId, variables); } public AsteriskChannel originateToApplication(String channel, String application, String data, long timeout) throws ManagerCommunicationException, NoSuchChannelException { return impl.originateToApplication(channel, application, data, timeout); } public AsteriskChannel originateToApplication(String channel, String application, String data, long timeout, CallerId callerId, Map<String, String> variables) throws ManagerCommunicationException, NoSuchChannelException { return impl.originateToApplication(channel, application, data, timeout, + callerId, variables); } public void originateToApplicationAsync(String channel, String application, String data, long timeout, CallerId callerId, Map<String, String> variables, OriginateCallback cb) throws ManagerCommunicationException { impl.originateToApplicationAsync(channel, application, data, timeout, callerId, variables, cb); } public void originateToApplicationAsync(String channel, String application, String data, long timeout, OriginateCallback cb) throws ManagerCommunicationException { impl.originateToApplicationAsync(channel, application, data, timeout, cb); } public void originateToExtensionAsync(String channel, String context, String exten, int priority, long timeout, CallerId callerId, Map<String, String> variables, OriginateCallback cb) throws ManagerCommunicationException

{ impl.originateToExtensionAsync(channel, context, exten, priority, timeout, callerId, variables, cb); } public void originateToExtensionAsync(String channel, String context, String exten, int priority, long timeout, OriginateCallback cb) throws ManagerCommunicationException { impl.originateToExtensionAsync(channel, context, exten, priority, timeout, cb); } public Collection<AsteriskChannel> getChannels() throws ManagerCommunicationException { return impl.getChannels(); } public AsteriskChannel getChannelByName(String name) throws ManagerCommunicationException { return impl.getChannelByName(name); } public AsteriskChannel getChannelById(String id) throws ManagerCommunicationException { return impl.getChannelById(id); } public Collection<MeetMeRoom> getMeetMeRooms() throws ManagerCommunicationException { return impl.getMeetMeRooms(); } public MeetMeRoom getMeetMeRoom(String name) throws ManagerCommunicationException { return impl.getMeetMeRoom(name); } public Collection<AsteriskQueue> getQueues() throws ManagerCommunicationException

{ return impl.getQueues(); } public String getVersion() throws ManagerCommunicationException { return impl.getVersion(); } public ConfigFile getConfig(String filename) throws ManagerCommunicationException { return impl.getConfig(filename); } public int[] getVersion(String file) throws ManagerCommunicationException { return impl.getVersion(file); } public String getGlobalVariable(String variable) throws ManagerCommunicationException { return impl.getGlobalVariable(variable); } public void setGlobalVariable(String variable, String value) throws ManagerCommunicationException { impl.setGlobalVariable(variable, value); } public Collection<Voicemailbox> getVoicemailboxes() throws ManagerCommunicationException { return impl.getVoicemailboxes(); } public List<String> executeCliCommand(String command) throws ManagerCommunicationException { return impl.executeCliCommand(command); } public void addAsteriskServerListener(AsteriskServerListener listener) throws ManagerCommunicationException

{ impl.addAsteriskServerListener(listener); } public void removeAsteriskServerListener(AsteriskServerListener listener) { impl.removeAsteriskServerListener(listener); } public void shutdown() { throw new UnsupportedOperationException("You are not supposed to call shutdown yourself on this implementation. Use stop() instead"); } public List<PeerEntryEvent> getPeerEntries() throws ManagerCommunicationException { return impl.getPeerEntries(); } public DbGetResponseEvent dbGet(String family, String key) throws ManagerCommunicationException { return impl.dbGet(family,key); } public void dbDel(String family, String key) throws ManagerCommunicationException { impl.dbDel(family, key); } public void dbPut(String family, String key, String value) throws ManagerCommunicationException { impl.dbPut(family, key, value); } public AsteriskChannel getChannelByNameAndActive(String name) throws ManagerCommunicationException { return impl.getChannelByNameAndActive(name); } /* GMI PRIVATE */ public ManagerResponse getSipShowPeerResponse(String sippeer) throws ManagerCommunicationException {

return impl.getSipShowPeerResponse(sippeer); } public Collection<AsteriskAgent> getAgents() throws ManagerCommunicationException { return impl.getAgents(); } private ManagerConnection createNewConnection() { ManagerConnectionImpl myConnection = new ManagerConnectionImpl(); myConnection.setHostname(hostname); myConnection.setUsername(username); myConnection.setPassword(password); myConnection.setPort(port); myConnection.setSsl(ssl); myConnection.setSocketTimeout(socketTimeout); myConnection.setSocketReadTimeout(socketReadTimeout); return myConnection; } public synchronized void start() { if (started) { return; } impl.setManagerConnection(createNewConnection()); // This thread will loop until the first successful connection // Reconnection will be handled by the connection itself (ConnectEvent) this.initThread = new FirstInitializationThread(); started = true; } public synchronized void stop() { if (! started) { return; } if (this.initThread != null && ! this.initThread.isDone()) { initThread.abort(); }

initThread = null; impl.shutdown(); started = false; } class FirstInitializationThread implements Runnable { Thread myThread; private boolean abort = false; private boolean done = false; FirstInitializationThread() { myThread = new Thread(this); myThread.setName("First initialization thread"); myThread.start(); }

public void run() { while (! impl.wasInitialized() && ! abort ) try { impl.initialize(); } catch (ManagerCommunicationException e) { try { Thread.sleep(1000); } catch (InterruptedException e1) { // swallow } } done = true; } void abort() { abort = true; // Interrupt sleep if (myThread != null) myThread.interrupt(); // Free resources myThread = null; }

boolean isDone() { return done; } } }

private SipEventListenerTest managerEventListener; private ManagerConnection managerConnection; private Logger log = Logger.getLogger(AsteriskManagerTest.class); private OriginateAction asteriskAction = null; public AsteriskManagerTest(String asteriskHost, int asteriskManagerPort, String asteriskManagerUser, String asteriskManagerPsw) { ManagerConnectionFactory factory = new ManagerConnectionFactory(asteriskHost, asteriskManagerPort, asteriskManagerUser, asteriskManagerPsw); this.managerConnection = factory.createManagerConnection(); log.debug("Creata connessione al server Asterisk " + managerConnection.getState()); } @Override public void run() { try { managerConnection.addEventListener(this.managerEventListener); managerConnection.login(); //CONTROLLO LA VALIDITA' DELL'AZIONE log.debug("getAsteriskAction().getChannel() " + getAsteriskAction().getChannel()); log.debug("getAsteriskAction().getContext() " + getAsteriskAction().getContext()); log.debug("getAsteriskAction().getExten() " + getAsteriskAction().getExten()); ResponseEvents risposte = managerConnection.sendEventGeneratingAction(getAsteriskAction(), 3000000); managerConnection.logoff(); this.managerEventListener = null;

try { Thread.sleep(10000); } catch (InterruptedException ex) { } } catch (IllegalStateException ex) { log.error("Illegal State Exception", ex); } catch (IOException ex) { log.error("IO Exception", ex); } catch (AuthenticationFailedException ex) { log.error("AuthenticationFailedException", ex); } catch (TimeoutException ex) { log.info("TimeoutException" + ex.getMessage()); } log.info("**************************** FINE DEL RUN() ASTERISK_MANAGER ***************************************************"); } public static void main(String[] args) throws Exception { AsteriskManagerTest manager = null; for (int i = 0; i < 2; i++) { manager = new AsteriskManagerTest("host", 5038, "manager", "psw"); OriginateAction action = new OriginateAction(); if (i == 0) { action.setChannel("SIP/trunk/number1"); } else { action.setChannel("SIP/ehiweb/number2"); } action.setContext("outgoing"); action.setExten("s"); action.setPriority(new Integer(1)); action.setTimeout(new Long(30000)); action.setVariable("data", "12/01/18/30"); action.setActionId("PROVA"); manager.setAsteriskAction(action); //LISTENER manager.setManagerEventListener(new SipEventListenerTest()); System.out.println("**************************** START THREAD N." + i + " ASTERISK_MANAGER ***************************************************"); manager.start(); } }

/** * @return the managerEventListener */ public ManagerEventListener getManagerEventListener() { return managerEventListener; } /** * @param managerEventListener the managerEventListener to set */ public void setManagerEventListener(SipEventListenerTest managerEventListener) { this.managerEventListener = managerEventListener; } /** * @return the asteriskAction */ public OriginateAction getAsteriskAction() { return asteriskAction; } /** * @param asteriskAction the asteriskAction to set */ public void setAsteriskAction(OriginateAction asteriskAction) { this.asteriskAction = asteriskAction; } }

public class SipEventListenerTest extends CallManagerEvent implements ManagerEventListener { @Override public void onManagerEvent(ManagerEvent event) { log.debug("Event " + ((AbstractChannelEvent) event).getUniqueId() + " - " + event); } }

import import import import import

java.io.IOException; java.util.ArrayList; java.util.Collection; java.util.List; java.util.regex.Pattern;

import org.asteriskjava.manager.AuthenticationFailedException; import org.asteriskjava.manager.ManagerConnection; import org.asteriskjava.manager.ManagerConnectionFactory; import org.asteriskjava.manager.ManagerEventListener; import org.asteriskjava.manager.TimeoutException; import org.asteriskjava.manager.action.CommandAction; import org.asteriskjava.manager.action.StatusAction; import org.asteriskjava.manager.event.ManagerEvent; import org.asteriskjava.manager.response.CommandResponse; import org.asteriskjava.manager.response.ManagerError; import org.asteriskjava.manager.response.ManagerResponse; import org.bigbluebutton.webconference.voice.asterisk.konference.events.Confe renceJoinEvent; import org.bigbluebutton.webconference.voice.asterisk.konference.events.Confe renceLeaveEvent; import org.bigbluebutton.webconference.voice.asterisk.konference.events.Confe renceMemberMuteEvent; import org.bigbluebutton.webconference.voice.asterisk.konference.events.Confe renceMemberUnmuteEvent; import org.bigbluebutton.webconference.voice.asterisk.konference.events.Confe renceStateEvent;

public class HelloEvents implements ManagerEventListener { private static final String KONFERENCE_LIST_COMMAND = "konference list"; private static final Pattern KONFERENCE_LIST_PATTERN = Pattern.compile("^MemberId:(.+)CIDName:(.+)CID:(.+)Muted:(.+)UniqueID: (.+)ConfName:(.+)Speaking:(.+)Channel:(.+)$"); private ManagerConnection managerConnection; public HelloEvents() throws IOException { ManagerConnectionFactory factory = new ManagerConnectionFactory( "192.168.0.120", "bbb", "secret"); this.managerConnection = factory.createManagerConnection(); managerConnection.registerUserEventClass(ConferenceJoinEvent.class); managerConnection.registerUserEventClass(ConferenceLeaveEvent.class); managerConnection.registerUserEventClass(ConferenceStateEvent.class); managerConnection.registerUserEventClass(ConferenceMemberMuteEvent.cla ss); managerConnection.registerUserEventClass(ConferenceMemberUnmuteEvent.c lass); } public void run() throws IOException, AuthenticationFailedException, TimeoutException, InterruptedException { // register for events managerConnection.addEventListener(this); // connect to Asterisk and log in managerConnection.login(); // request channel state managerConnection.sendAction(new StatusAction()); // wait 10 seconds for events to come in Thread.sleep(10000); // // } private void populateRoom(String room) { final CommandAction meetMeListAction; ManagerResponse response = null; final List<String> lines; final Collection<Integer> userNumbers = new ArrayList<Integer>(); // list of user numbers in the room meetMeListAction = new CommandAction(KONFERENCE_LIST_COMMAND + " " + room); populateRoom("85115"); // and finally log off and disconnect managerConnection.logoff();

try { response = managerConnection.sendAction(meetMeListAction); } catch (TimeoutException e) { System.out.println("Unable to send \"" + KONFERENCE_LIST_COMMAND + "\" command"); return; } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (response instanceof ManagerError) { System.out.println("Unable to send \"" + KONFERENCE_LIST_COMMAND + "\" command: " + response.getMessage()); return; } if (!(response instanceof CommandResponse)) { System.out.println("Response to \"" + KONFERENCE_LIST_COMMAND + "\" command is not a CommandResponse but " + response.getClass()); return; } lines = ((CommandResponse) response).getResult(); for (String line : lines) { System.out.println(line); /* final Matcher matcher; final Integer userNumber; boolean muted = false; boolean talking = false; ConferenceMemberImpl channelUser; ConferenceMemberImpl roomUser; matcher = KONFERENCE_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; } roomUser = room.getUser(userNumber); if (roomUser != null && roomUser.getChannel() != channel) { room.removeUser(roomUser); roomUser = null; } if (channelUser == null && roomUser == null) { final ConferenceMemberImpl user; // using the current date as dateJoined is not correct but we // don't have anything that is better user = new ConferenceMemberImpl(server, room, userNumber, channel, DateUtil.getDate()); user.setMuted(muted); user.setTalking(talking); room.addUser(user); channel.setMeetMeUserImpl(user); server.fireNewMeetMeUser(user); } else if (channelUser != null && roomUser == null) { channelUser.setMuted(muted); room.addUser(channelUser); } else if (channelUser == null) { roomUser.setMuted(muted); channel.setMeetMeUserImpl(roomUser); } else { if (channelUser != roomUser) { logger.error("Inconsistent state: channelUser != roomUser, channelUser=" + channelUser + ", roomUser=" + roomUser); } } */ } /* Collection<ConferenceMemberImpl> users = room.getUserImpls(); Collection<ConferenceMemberImpl> usersToRemove = new ArrayList<ConferenceMemberImpl>(); for (ConferenceMemberImpl user : users) { if (!userNumbers.contains(user.getUserNumber())) { // remove user as he is no longer in the room usersToRemove.add(user); } } for (ConferenceMemberImpl user : usersToRemove) { user.left(DateUtil.getDate()); room.removeUser(user); user.getChannel().setMeetMeUserImpl(null); } */ }

public void onManagerEvent(ManagerEvent event) { // just print received events System.out.println(event); } public static void main(String[] args) throws Exception { HelloEvents helloEvents; helloEvents = new HelloEvents(); helloEvents.run(); while (true) { } } }

You might also like