public void onEvent(PlayerEvent event) {

      Player player = event.getSource();
      MediaGroup mg = player.getContainer();
      if (!isBye) {
        if (event.isSuccessful() && (PlayerEvent.PLAY_COMPLETED == event.getEventType())) {

          MediaSession mediaSession = event.getSource().getMediaSession();

          SipSession sipSession = (SipSession) mediaSession.getAttribute("SIP_SESSION");

          sipSession.setAttribute("MEDIA_GROUP", mg);

          SipApplicationSession sipAppSession = sipSession.getApplicationSession();

          try {
            Recorder recoredr = mg.getRecorder();
            logger.info("recording the user at " + RECORDER);
            URI prompt = URI.create(RECORDER);

            recoredr.record(prompt, null, null);

            TimerService timer = (TimerService) getServletContext().getAttribute(TIMER_SERVICE);
            timer.createTimer(sipAppSession, RECORDING_DELAY, false, sipSession.getId());

          } catch (MsControlException e) {
            logger.error("An unexpected error happened ", e);
          }
        } else {
          logger.error("Player didn't complete successfully ");
        }
      }
    }
  @Override
  public synchronized void forwardTo(final Call call, final Map<String, String> headers)
      throws SignalException {
    if (!(call instanceof SIPCall)) {
      throw new UnsupportedOperationException("Cannot forward to non-SIPCall.");
    }
    if (_req.isInitial()) {
      throw new IllegalArgumentException("Cannot forward initial SIP request.");
    }
    final SIPCallImpl scall = (SIPCallImpl) call;
    if (!scall.isAnswered()) {
      throw new IllegalStateException("Cannot forward to no-answered call.");
    }
    this.checkState();

    _forwarded = true;
    final SipSession session = scall.getSipSession();
    final SipServletRequest req = session.createRequest(_req.getMethod());
    SIPHelper.addHeaders(req, headers);
    SIPHelper.copyContent(_req, req);
    SIPHelper.linkSIPMessage(_req, req);
    try {
      req.send();
    } catch (final IOException e) {
      throw new SignalException(e);
    }
  }
 public void timeout(ServletTimer timer, SipSession sipSession) {
   serverEntryLog();
   String reasonPhrase;
   if (sipSession.getAttribute("cancelled") != null) {
     reasonPhrase = "got cancelled";
   } else {
     logger.error("***ERROR: didn't receive notification of CANCEL***");
     reasonPhrase = "didn't get cancelled";
   }
   try {
     SipServletRequest invite = (SipServletRequest) sipSession.getAttribute("invite");
     SipServletResponse resp = invite.createResponse(500, reasonPhrase);
     try {
       resp.send();
     } catch (IOException ex) {
       logger.error("***failed to send subsequent request***", ex);
     }
     logger.error(
         "***ERROR: sending final response after CANCEL didn't "
             + "cause IllegalStateException***");
   } catch (IllegalStateException ex) {
     logger.info(
         "===SUCCESS: sending final response after CANCEL " + "cause IllegalStateException===");
   }
 }
Beispiel #4
0
 public static SipServletRequest getLinkedRequest(SipServletMessage message) {
   SipSession linkedB2BUASession = getLinkedSession(message);
   if (linkedB2BUASession != null) {
     SipServletRequest linkedRequest =
         (SipServletRequest) linkedB2BUASession.getAttribute(B2BUA_LAST_REQUEST);
     return linkedRequest;
   }
   return null;
 }
Beispiel #5
0
  public SipServletRequest createRequest(String method) {
    if (_session == null) throw new IllegalStateException("Session not created");

    SipServletRequest request = _session.createRequest(method);
    if (_session.getState() == State.INITIAL && _outboundProxy != null)
      request.pushRoute(_outboundProxy);

    return request;
  }
Beispiel #6
0
 public static SipServletResponse getLinkedResponse(SipServletMessage message) {
   SipSession linkedB2BUASession = getLinkedSession(message);
   // if this is an ACK that belongs to a B2BUA session, then we proxy it to the other client
   if (linkedB2BUASession != null) {
     SipServletResponse response =
         (SipServletResponse) linkedB2BUASession.getAttribute(B2BUA_LAST_RESPONSE);
     return response;
   }
   return null;
 }
  @Override
  protected void preprocessState(SipSession session, State state) {
    BigInteger version = (BigInteger) session.getAttribute(Constants.VERSION_ATTRIBUTE);
    if (version == null) version = BigInteger.ZERO;
    else version = version.add(BigInteger.ONE);
    Watcherinfo watcherinfo = ((WatcherinfoDocument) state.getContent()).getWatcherinfo();

    watcherinfo.setVersion(version);
    session.setAttribute(Constants.VERSION_ATTRIBUTE, version);
  }
Beispiel #8
0
  private void initialize(SipServletRequest request) throws ServletException {
    if (_session != null) throw new ServletException("Dialog already started");

    _sessionHandler = new SessionHandler();
    _session = request.getSession();
    _session.setAttribute(MessageHandler.class.getName(), _sessionHandler);
    _session.setAttribute(INITIAL_REQUEST_ATTRIBUTE, request);

    _sessionHandler.setTimeout(_timeout);
    _sessionHandler.setCredentials(_credentials);
  }
 protected void doInvite(SipServletRequest req) throws ServletException, IOException {
   serverEntryLog();
   logger.debug("---doInvite---");
   SipServletResponse resp = req.createResponse(180);
   resp.send();
   // just set timer - we expect a CANCEL to arrive...
   SipSession sipSession = req.getSession();
   sipSession.setAttribute("invite", req);
   timerService.createTimer(
       req.getApplicationSession(), 5000, true, UasCancelServlet.class.getName());
 }
  @Override
  protected void doBye(SipServletRequest req) {
    SipSession session = req.getSession(false);
    SipSession linkedSession = (SipSession) session.getAttribute(Constant.LINKED_SESSION);

    logger.info("SIP BYE From : " + req.getFrom().toString());

    // caller session
    if (null != session.getAttribute(Constant.INVITE_USER_REQUEST)) {
      doBye(session, req);
    }
    // callee session
    else {
      logger.info("callee do bye!");
      doBye(linkedSession, req);
    }
  }
 @Override
 protected void doBye(SipServletRequest request) throws ServletException, IOException {
   logger.info("Got bye");
   SipSession session = request.getSession();
   SipSession linkedSession = (SipSession) session.getAttribute("LinkedSession");
   if (linkedSession != null) {
     SipServletRequest bye = linkedSession.createRequest("BYE");
     logger.info("Sending bye to " + linkedSession.getRemoteParty());
     bye.send();
   }
   CallStatusContainer calls =
       (CallStatusContainer) getServletContext().getAttribute("activeCalls");
   calls.removeCall(request.getFrom().getURI().toString(), request.getTo().getURI().toString());
   calls.removeCall(request.getTo().getURI().toString(), request.getFrom().getURI().toString());
   SipServletResponse ok = request.createResponse(SipServletResponse.SC_OK);
   ok.send();
 }
 @Observer("connectionOpen")
 public void doConnectionOpen(MsConnectionEvent event) throws IOException {
   conferenceEndpointName = event.getConnection().getEndpoint().getLocalName();
   SipServletRequest request = (SipServletRequest) sipSession.getAttribute("inviteRequest");
   SipServletResponse response = request.createResponse(200);
   response.setContent(event.getConnection().getLocalDescriptor(), "application/sdp");
   response.send();
 }
  @Override
  protected void doAck(SipServletRequest req) throws ServletException, IOException {
    SipSession sipSession = req.getSession();

    MediaSession ms = (MediaSession) sipSession.getAttribute("MEDIA_SESSION");
    try {
      MediaGroup mg = ms.createMediaGroup(MediaGroup.PLAYER_RECORDER_SIGNALDETECTOR);
      mg.addListener(new MyJoinEventListener());

      NetworkConnection nc = (NetworkConnection) sipSession.getAttribute("NETWORK_CONNECTION");
      mg.joinInitiate(Direction.DUPLEX, nc, this);

    } catch (MsControlException e) {
      logger.error(e);
      // Clean up media session
      terminate(sipSession, ms);
    }
  }
 @Observer("INVITE")
 @CreateProcess(definition = "demo")
 public void doInvite(SipServletRequest request) throws Exception {
   String sdp = new String((byte[]) request.getContent());
   request.createResponse(180).send();
   sipSession.setAttribute("inviteRequest", request);
   if (conferenceEndpointName == null) conferenceEndpointName = "media/trunk/Conference/$";
   mediaController.createConnection(conferenceEndpointName).modify("$", sdp);
 }
  public void onEvent(PlayerEvent event) {
    try {
      logger.info("ENDING CALL ");
      Player player = event.getSource();
      MediaGroup mg = player.getContainer();
      if (event.isSuccessful() && (PlayerEvent.PLAY_COMPLETED == event.getEventType())) {
        MediaSession session = (MediaSession) sipSession.getAttribute("mediaSession");
        session.release();
        Thread.sleep(1500);

        SipServletRequest byeRequest = sipSession.createRequest("BYE");
        byeRequest.send();
      }

    } catch (Exception e) {
      logger.error("Error", e);
    }
  }
  public void timeout(ServletTimer servletTimer) {

    String sessionId = (String) servletTimer.getInfo();
    logger.info("Timer fired on sip session " + sessionId);
    SipSession sipSession = servletTimer.getApplicationSession().getSipSession(sessionId);

    if (sipSession != null) {
      MediaGroup mediaGroup = (MediaGroup) sipSession.getAttribute("MEDIA_GROUP");
      if (mediaGroup != null) {
        logger.info("Timer fired, stopping the recording");
        try {
          mediaGroup.getRecorder().stop();
        } catch (MsControlException e) {
          logger.info("recording couldn't be stopped", e);
        }
      }
    } else {
      logger.info("the session has not been found, it may have been already invalidated");
    }
  }
  private void doBye(SipSession session, SipServletRequest request) {
    // send bye to its linked user session and notify
    SipSession reqSession = request.getSession(false);
    if (null == reqSession.getAttribute(Constant.INVITE_USER_REQUEST)) {
      logger.info("callee ok");
      SipServletRequest bye = session.createRequest(Constant.BYE);
      try {
        bye.send();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // send 200 OK to the session
    SipServletResponse resp = request.createResponse(SipServletResponse.SC_OK);
    try {
      resp.send();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Beispiel #18
0
  /** Update the dialog with the response. Could be needed if there has been multiple dialogs. */
  public void updateDialog(SipServletResponse response) {
    SipSession session = response.getSession();
    if (session.equals(_session)) return;

    if (!session.getCallId().equals(_session.getCallId()))
      throw new IllegalArgumentException(
          "Session " + session + " is not a derived session from " + _session);

    String localTag = response.getFrom().getParameter("tag");
    if (!localTag.equals(_session.getLocalParty().getParameter("tag"))
        && !localTag.equals(_session.getRemoteParty().getParameter("tag")))
      throw new IllegalArgumentException(
          "Session " + session + " is not a derived session from " + _session);

    _session = session;
  }
 public void doCancel(SipServletRequest req) throws IOException {
   serverEntryLog();
   logger.debug("---doCancel---");
   SipSession sipSession = req.getSession();
   sipSession.setAttribute("cancelled", Boolean.TRUE);
 }
  @Override
  protected void doSuccessResponse(SipServletResponse resp) throws ServletException, IOException {
    logger.info("Got OK");
    SipSession session = resp.getSession();

    if (resp.getStatus() == SipServletResponse.SC_OK) {

      Boolean inviteSent = (Boolean) session.getAttribute("InviteSent");
      if (inviteSent != null && inviteSent.booleanValue()) {
        return;
      }
      Address secondPartyAddress = (Address) resp.getSession().getAttribute("SecondPartyAddress");
      if (secondPartyAddress != null) {

        SipServletRequest invite =
            sipFactory.createRequest(
                resp.getApplicationSession(),
                "INVITE",
                session.getRemoteParty(),
                secondPartyAddress);

        logger.info("Found second party -- sending INVITE to " + secondPartyAddress);

        String contentType = resp.getContentType();
        if (contentType.trim().equals("application/sdp")) {
          invite.setContent(resp.getContent(), "application/sdp");
        }

        session.setAttribute("LinkedSession", invite.getSession());
        invite.getSession().setAttribute("LinkedSession", session);

        SipServletRequest ack = resp.createAck();
        invite.getSession().setAttribute("FirstPartyAck", ack);
        invite.getSession().setAttribute("FirstPartyContent", resp.getContent());

        Call call = (Call) session.getAttribute("call");

        // The call links the two sessions, add the new session to the call
        call.addSession(invite.getSession());
        invite.getSession().setAttribute("call", call);

        invite.send();

        session.setAttribute("InviteSent", Boolean.TRUE);
      } else {
        String cSeqValue = resp.getHeader("CSeq");
        if (cSeqValue.indexOf("INVITE") != -1) {
          logger.info("Got OK from second party -- sending ACK");

          SipServletRequest secondPartyAck = resp.createAck();
          SipServletRequest firstPartyAck =
              (SipServletRequest) resp.getSession().getAttribute("FirstPartyAck");

          //					if (resp.getContentType() != null &&
          // resp.getContentType().equals("application/sdp")) {
          firstPartyAck.setContent(resp.getContent(), "application/sdp");
          secondPartyAck.setContent(
              resp.getSession().getAttribute("FirstPartyContent"), "application/sdp");
          //					}

          firstPartyAck.send();
          secondPartyAck.send();
        }
      }
    }
  }
Beispiel #21
0
  /**
   * @param request
   * @param client
   * @param toClient
   * @throws IOException
   */
  public static boolean redirectToB2BUA(
      final SipServletRequest request,
      final Client client,
      Client toClient,
      DaoManager storage,
      SipFactory sipFactory)
      throws IOException {
    request.getSession().setAttribute("lastRequest", request);
    if (logger.isInfoEnabled()) {
      logger.info("B2BUA (p2p proxy): Got request:\n" + request.getMethod());
      logger.info(
          String.format(
              "B2BUA: Proxying a session between %s and %s", client.getUri(), toClient.getUri()));
    }

    if (daoManager == null) {
      daoManager = storage;
    }

    String user = ((SipURI) request.getTo().getURI()).getUser();

    final RegistrationsDao registrations = daoManager.getRegistrationsDao();
    final Registration registration = registrations.getRegistration(user);
    if (registration != null) {
      final String location = registration.getLocation();
      SipURI to;
      SipURI from;
      try {
        to = (SipURI) sipFactory.createURI(location);
        from =
            (SipURI)
                sipFactory.createURI(
                    (registrations.getRegistration(client.getLogin())).getLocation());

        final SipSession incomingSession = request.getSession();
        // create and send the outgoing invite and do the session linking
        incomingSession.setAttribute(B2BUA_LAST_REQUEST, request);
        SipServletRequest outRequest =
            sipFactory.createRequest(
                request.getApplicationSession(),
                request.getMethod(),
                request.getFrom().getURI(),
                request.getTo().getURI());
        outRequest.setRequestURI(to);

        if (request.getContent() != null) {
          final byte[] sdp = request.getRawContent();
          String offer = null;
          if (request.getContentType().equalsIgnoreCase("application/sdp")) {
            // Issue 308: https://telestax.atlassian.net/browse/RESTCOMM-308
            String externalIp = request.getInitialRemoteAddr();
            // Issue 306: https://telestax.atlassian.net/browse/RESTCOMM-306
            final String initialIpBeforeLB = request.getHeader("X-Sip-Balancer-InitialRemoteAddr");
            try {
              if (initialIpBeforeLB != null && !initialIpBeforeLB.isEmpty()) {
                offer = patch(sdp, initialIpBeforeLB);
              } else {
                offer = patch(sdp, externalIp);
              }
            } catch (SdpException e) {
              logger.error("Unexpected exception while patching sdp ", e);
            }
          }
          if (offer != null) {
            outRequest.setContent(offer, request.getContentType());
          } else {
            outRequest.setContent(sdp, request.getContentType());
          }
        }

        final SipSession outgoingSession = outRequest.getSession();
        if (request.isInitial()) {
          incomingSession.setAttribute(B2BUA_LINKED_SESSION, outgoingSession);
          outgoingSession.setAttribute(B2BUA_LINKED_SESSION, incomingSession);
        }
        outgoingSession.setAttribute(B2BUA_LAST_REQUEST, outRequest);
        request.createResponse(100).send();
        // Issue #307: https://telestax.atlassian.net/browse/RESTCOMM-307
        request.getSession().setAttribute("toInetUri", to);
        outRequest.send();
        outRequest.getSession().setAttribute("fromInetUri", from);

        final CallDetailRecord.Builder builder = CallDetailRecord.builder();
        builder.setSid(Sid.generate(Sid.Type.CALL));
        builder.setDateCreated(DateTime.now());
        builder.setAccountSid(client.getAccountSid());
        builder.setTo(toClient.getFriendlyName());
        builder.setCallerName(client.getFriendlyName());
        builder.setFrom(client.getFriendlyName());
        // builder.setForwardedFrom(callInfo.forwardedFrom());
        // builder.setPhoneNumberSid(phoneId);
        builder.setStatus(CallStateChanged.State.QUEUED.name());
        builder.setDirection("Client-To-Client");
        builder.setApiVersion(client.getApiVersion());
        builder.setPrice(new BigDecimal("0.00"));
        // TODO implement currency property to be read from Configuration
        builder.setPriceUnit(Currency.getInstance("USD"));
        final StringBuilder buffer = new StringBuilder();
        buffer.append("/").append(client.getApiVersion()).append("/Accounts/");
        buffer.append(client.getAccountSid().toString()).append("/Calls/");
        buffer.append(client.getSid().toString());
        final URI uri = URI.create(buffer.toString());
        builder.setUri(uri);

        CallDetailRecordsDao records = daoManager.getCallDetailRecordsDao();
        CallDetailRecord callRecord = builder.build();
        records.addCallDetailRecord(callRecord);

        incomingSession.setAttribute(CDR_SID, callRecord.getSid());
        outgoingSession.setAttribute(CDR_SID, callRecord.getSid());

        return true; // successfully proxied the SIP request between two registered clients
      } catch (ServletParseException badUriEx) {
        if (logger.isInfoEnabled()) {
          logger.info(
              String.format("B2BUA: Error parsing Client Contact URI: %s", location), badUriEx);
        }
      }
    }
    return false;
  }