View Javadoc

1   /*
2    *  Copyright 2004-2006 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 org.asteriskjava.manager.internal;
18  
19  import java.io.IOException;
20  
21  import org.asteriskjava.AsteriskVersion;
22  import org.asteriskjava.manager.action.ManagerAction;
23  import org.asteriskjava.util.Log;
24  import org.asteriskjava.util.LogFactory;
25  import org.asteriskjava.util.SocketConnectionFacade;
26  
27  
28  /***
29   * Default implementation of ManagerWriter interface.
30   * 
31   * @author srt
32   * @version $Id: ManagerWriterImpl.java 636 2007-04-17 00:26:18Z srt $
33   */
34  public class ManagerWriterImpl implements ManagerWriter
35  {
36      /***
37       * Instance logger.
38       */
39      private final Log logger = LogFactory.getLog(getClass());
40  
41      /***
42       * The action builder utility to convert ManagerAction to a String suitable to be sent to the
43       * asterisk server.
44       */
45      private final ActionBuilder actionBuilder;
46  
47      private SocketConnectionFacade socket;
48  
49      /***
50       * Creates a new ManagerWriter.
51       */
52      public ManagerWriterImpl()
53      {
54          this.actionBuilder = new ActionBuilderImpl();
55      }
56  
57      public void setTargetVersion(AsteriskVersion version)
58      {
59          actionBuilder.setTargetVersion(version);
60      }
61  
62      public synchronized void setSocket(final SocketConnectionFacade socket)
63      {
64          this.socket = socket;
65      }
66  
67      public synchronized void sendAction(final ManagerAction action, final String internalActionId) throws IOException
68      {
69          final String actionString;
70  
71          if (socket == null)
72          {
73              throw new IllegalStateException("Unable to send action: socket is null");
74          }
75  
76          actionString = actionBuilder.buildAction(action, internalActionId);
77  
78          socket.write(actionString);
79          socket.flush();
80  
81          // TODO tracing
82          //logger.debug("Sent " + action.getAction() + " action with actionId '" + action.getActionId() + "':\n" + actionString);
83      }
84  }