View Javadoc

1   /*
2    * Copyright  2004-2005 Stefan Reuter
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   *
16   */
17  package net.sf.asterisk.manager.impl;
18  
19  import java.io.IOException;
20  
21  import net.sf.asterisk.AsteriskVersion;
22  import net.sf.asterisk.io.SocketConnectionFacade;
23  import net.sf.asterisk.manager.ActionBuilder;
24  import net.sf.asterisk.manager.ManagerWriter;
25  import net.sf.asterisk.manager.action.ManagerAction;
26  import net.sf.asterisk.util.Log;
27  import net.sf.asterisk.util.LogFactory;
28  
29  /***
30   * Default implementation of ManagerWriter interface.
31   * 
32   * @author srt
33   * @version $Id: ManagerWriterImpl.java,v 1.4 2005/11/08 15:25:18 srt Exp $
34   */
35  public class ManagerWriterImpl implements ManagerWriter
36  {
37      /***
38       * Instance logger.
39       */
40      private final Log logger = LogFactory.getLog(getClass());
41  
42      /***
43       * The action builder utility to convert ManagerAction to a String suitable to be sent to the
44       * asterisk server.
45       */
46      private final ActionBuilder actionBuilder;
47  
48      private SocketConnectionFacade socket;
49  
50      /***
51       * Creates a new ManagerWriter.
52       */
53      public ManagerWriterImpl()
54      {
55          this.actionBuilder = new ActionBuilderImpl();
56      }
57  
58      public void setTargetVersion(AsteriskVersion version)
59      {
60          actionBuilder.setTargetVersion(version);
61      }
62  
63      public synchronized void setSocket(final SocketConnectionFacade socket)
64      {
65          this.socket = socket;
66      }
67  
68      public synchronized void sendAction(final ManagerAction action, final String internalActionId) throws IOException
69      {
70          final String actionString;
71  
72          if (socket == null)
73          {
74              throw new IllegalStateException("Unable to send action: socket is null");
75          }
76  
77          actionString = actionBuilder.buildAction(action, internalActionId);
78  
79          socket.write(actionString);
80          socket.flush();
81  
82          logger.debug("Sent " + action.getAction() + " action with actionId '" + action.getActionId() + "':\n"
83                  + actionString);
84      }
85  }