public void connectionOpenResponse(MsConnectionEvent event, SipServletResponse response) {
    logger.info("connection opened " + event);

    String sdp = event.getConnection().getLocalDescriptor();
    SipServletRequest ack = response.createAck();

    try {
      ack.setContent(sdp, "application/sdp");
      ack.send();
    } catch (Exception e) {
      logger.error(e);
    }
    provider = ConferenceCenter.getInstance().getProvider();
    MsConnection connection = event.getConnection();
    MsEndpoint endpoint = connection.getEndpoint();
    MsSession session = connection.getSession();
    String callerName = response.getTo().getURI().toString();

    ConferenceParticipant participant =
        new EndpointConferenceParticipant(callerName, endpoint, session, response, connection);

    String key = SipGwtConferenceConsole.CONFERENCE_NAME;

    ConferenceCenter.getInstance().getConference(key).joinParticipant(participant);
  }
  public void connectionOpenRequest(MsConnectionEvent event, SipServletRequest inviteRequest) {
    logger.info("connection opened " + event);

    String sdp = event.getConnection().getLocalDescriptor();
    SipServletResponse sipServletResponse = inviteRequest.createResponse(SipServletResponse.SC_OK);

    try {
      sipServletResponse.setContent(sdp, "application/sdp");
      sipServletResponse.send();
    } catch (Exception e) {
      logger.error(e);
    }
    provider = ConferenceCenter.getInstance().getProvider();
    MsConnection connection = event.getConnection();
    MsEndpoint endpoint = connection.getEndpoint();
    MsSession session = connection.getSession();
    String callerName = inviteRequest.getFrom().getURI().toString();

    ConferenceParticipant participant =
        new EndpointConferenceParticipant(callerName, endpoint, session, inviteRequest, connection);

    String key = ((SipURI) inviteRequest.getTo().getURI()).getUser();

    ConferenceCenter.getInstance().getConference(key).joinParticipant(participant);
  }
  protected void doRegister(SipServletRequest req) throws ServletException, IOException {
    logger.info("Received register request: " + req.getTo());
    int response = SipServletResponse.SC_OK;
    SipServletResponse resp = req.createResponse(response);
    HashMap<String, String> users =
        (HashMap<String, String>) getServletContext().getAttribute("registeredUsersMap");
    if (users == null) users = new HashMap<String, String>();
    getServletContext().setAttribute("registeredUsersMap", users);

    Address address = req.getAddressHeader(CONTACT_HEADER);
    String fromURI = req.getFrom().getURI().toString();

    int expires = address.getExpires();
    if (expires < 0) {
      expires = req.getExpires();
    }
    if (expires == 0) {
      users.remove(fromURI);
      logger.info("User " + fromURI + " unregistered");
    } else {
      resp.setAddressHeader(CONTACT_HEADER, address);
      users.put(fromURI, address.getURI().toString());
      logger.info("User " + fromURI + " registered with an Expire time of " + expires);
    }

    resp.send();
  }
 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===");
   }
 }
 @Override
 protected void handleAck(final SIPCallImpl call, final SipServletRequest req) throws Exception {
   final SipServletResponse res =
       (SipServletResponse) req.getSession().getAttribute(REINVITE_PEER_RES);
   final SipServletRequest newReq = res.createAck();
   SIPHelper.copyContent(req, newReq);
   newReq.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 doErrorResponse(SipServletResponse resp) throws ServletException, IOException {
   // If someone rejects it remove the call from the table
   CallStatusContainer calls =
       (CallStatusContainer) getServletContext().getAttribute("activeCalls");
   calls.removeCall(resp.getFrom().getURI().toString(), resp.getTo().getURI().toString());
   calls.removeCall(resp.getTo().getURI().toString(), resp.getFrom().getURI().toString());
 }
示例#8
0
 protected synchronized void doInvite(final Map<String, String> headers) throws IOException {
   if (_cstate == SIPCall.State.INVITING) {
     setSIPCallState(SIPCall.State.RINGING);
     final SipServletResponse res = _invite.createResponse(SipServletResponse.SC_RINGING);
     SIPHelper.addHeaders(res, headers);
     res.send();
   }
 }
示例#9
0
 protected synchronized void doPrack(final SipServletRequest req) throws IOException {
   if (_cstate == SIPCall.State.PROGRESSED) {
     final SipServletResponse res = req.createResponse(SipServletResponse.SC_OK);
     if (getLocalSDP() != null) {
       res.setContent(getLocalSDP(), "application/sdp");
     }
     res.send();
   }
 }
 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
 public synchronized void accept(final Map<String, String> headers) throws SignalException {
   this.checkState();
   _accepted = true;
   final SipServletResponse res = _req.createResponse(SipServletResponse.SC_OK);
   SIPHelper.addHeaders(res, headers);
   try {
     res.send();
   } catch (final IOException e) {
     throw new SignalException(e);
   }
 }
 @Override
 public synchronized void reject(final Reason reason, final Map<String, String> headers)
     throws SignalException {
   this.checkState();
   _rejected = true;
   final SipServletResponse res =
       _req.createResponse(reason == null ? Reason.DECLINE.getCode() : reason.getCode());
   SIPHelper.addHeaders(res, headers);
   try {
     res.send();
   } catch (final IOException e) {
     throw new SignalException(e);
   }
 }
 @Override
 protected void doInvite(SipServletRequest request) throws ServletException, IOException {
   if (logger.isInfoEnabled()) {
     logger.info("Simple Servlet: Got request:\n" + request.getMethod());
   }
   SipServletResponse sipServletResponse = request.createResponse(SipServletResponse.SC_RINGING);
   sipServletResponse.send();
   sipServletResponse = request.createResponse(SipServletResponse.SC_OK);
   sipServletResponse.send();
   if (CALLEE_SEND_BYE.equalsIgnoreCase(((SipURI) request.getTo().getURI()).getUser())) {
     TimerService timer = (TimerService) getServletContext().getAttribute(TIMER_SERVICE);
     timer.createTimer(
         request.getApplicationSession(), byeDelay, false, request.getSession().getId());
   }
 }
示例#14
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;
  }
 @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();
 }
示例#16
0
  @Override
  public synchronized void reject(final Reason reason, final Map<String, String> headers)
      throws SignalException {
    checkState();
    _rejected = true;
    setSIPCallState(SIPCall.State.REJECTED);

    terminate(CallCompleteEvent.Cause.DECLINE, null, headers);

    try {
      final SipServletResponse res =
          _invite.createResponse(reason == null ? Reason.DECLINE.getCode() : reason.getCode());
      SIPHelper.addHeaders(res, headers);
      res.send();
    } catch (final IOException e) {
      throw new SignalException(e);
    }
  }
示例#17
0
  /**
   * Ensure that the servlet is not invoked if session is invalidated.
   *
   * <p>See http://jira.cipango.org/browse/CIPANGO-121
   *
   * <pre>
   *  Alice        Proxy       Bob
   * 1  | INVITE     |          |
   *    |----------->|          |
   * 2  |            | INVITE   |
   *    |            |--------->|
   * 3  |            |      200 |
   *    |            |<---------|
   * 4  |        200 |          |
   *    |<-----------|          |
   * 5  | ACK        |          |
   *    |----------->|          |
   * 6  |            | ACK      |
   *    |            |--------->|
   * 7  | BYE        |          |
   *    |----------->|          |
   * 8  |            | BYE      |
   *    |            |--------->|
   * 9  |            |      200 |
   *    |            |<---------|
   * 10 |        200 |          |
   *    |<-----------|          |
   * </pre>
   */
  @Test
  public void testInvalidateBefore200() throws Exception {
    Endpoint bob = createEndpoint("bob");
    UaRunnable callB = new UasScript.OkBye(bob.getUserAgent());

    callB.start();

    SipServletRequest request = _ua.createRequest(SipMethods.INVITE, bob.getUri());
    request.setRequestURI(bob.getContact().getURI());
    Call callA = _ua.createCall(request);
    assertThat(callA.waitForResponse(), isSuccess());
    callA.createAck().send();
    callA.createBye().send();

    SipServletResponse response = callA.waitForResponse();
    assertThat(response, isSuccess());
    assertThat(response.getHeader("error"), is(nullValue()));
  }
示例#18
0
  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();
    }
  }
示例#19
0
  @Override
  public synchronized void redirect(final Endpoint o, final Map<String, String> headers)
      throws SignalException {
    checkState();
    _redirected = true;
    setSIPCallState(SIPCall.State.REDIRECTED);

    terminate(CallCompleteEvent.Cause.REDIRECT, null, headers);

    if (o instanceof SIPEndpoint) {
      final SipServletResponse res =
          _invite.createResponse(SipServletResponse.SC_MOVED_TEMPORARILY);
      res.setHeader("Contact", ((SIPEndpoint) o).getURI().toString());
      SIPHelper.addHeaders(res, headers);
      try {
        res.send();
      } catch (final IOException e) {
        throw new SignalException(e);
      }
    } else {
      throw new IllegalArgumentException("Unable to redirect the call to a non-SIP participant.");
    }
  }
示例#20
0
 @Override
 public synchronized void onEvent(final SdpPortManagerEvent event) {
   if (getSIPCallState() == SIPCall.State.PROGRESSING) {
     try {
       final byte[] sdp = event.getMediaServerSdp();
       this.setLocalSDP(sdp);
       final SipServletResponse res =
           getSipInitnalRequest().createResponse(SipServletResponse.SC_SESSION_PROGRESS);
       res.setContent(sdp, "application/sdp");
       try {
         res.sendReliably();
       } catch (final Rel100Exception e) {
         LOG.warn("", e);
         res.send();
       }
       setSIPCallState(SIPCall.State.PROGRESSED);
       this.notifyAll();
     } catch (final IOException e) {
       LOG.warn("", e);
     }
   }
   super.onEvent(event);
 }
示例#21
0
 List<NameValuePair> parameters() {
   final List<NameValuePair> parameters = new ArrayList<NameValuePair>();
   final String callSid = callInfo.sid().toString();
   parameters.add(new BasicNameValuePair("CallSid", callSid));
   final String accountSid = accountId.toString();
   parameters.add(new BasicNameValuePair("AccountSid", accountSid));
   final String from = (callInfo.from());
   parameters.add(new BasicNameValuePair("From", from));
   final String to = (callInfo.to());
   parameters.add(new BasicNameValuePair("To", to));
   final String state = callState.toString();
   parameters.add(new BasicNameValuePair("CallStatus", state));
   parameters.add(new BasicNameValuePair("ApiVersion", version));
   final String direction = callInfo.direction();
   parameters.add(new BasicNameValuePair("Direction", direction));
   final String callerName = callInfo.fromName();
   parameters.add(new BasicNameValuePair("CallerName", callerName));
   final String forwardedFrom = callInfo.forwardedFrom();
   parameters.add(new BasicNameValuePair("ForwardedFrom", forwardedFrom));
   // logger.info("Type " + callInfo.type());
   if (CreateCall.Type.SIP == callInfo.type()) {
     // Adding SIP OUT Headers and SipCallId for
     // https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out
     SipServletResponse lastResponse = callInfo.lastResponse();
     // logger.info("lastResponse " + lastResponse);
     if (lastResponse != null) {
       final int statusCode = lastResponse.getStatus();
       final String method = lastResponse.getMethod();
       // See https://www.twilio.com/docs/sip/receiving-sip-headers
       // Headers on the final SIP response message (any 4xx or 5xx message or the final BYE/200)
       // are posted to the
       // Dial action URL.
       if ((statusCode >= 400 && "INVITE".equalsIgnoreCase(method))
           || (statusCode >= 200 && statusCode < 300 && "BYE".equalsIgnoreCase(method))) {
         final String sipCallId = lastResponse.getCallId();
         parameters.add(new BasicNameValuePair("DialSipCallId", sipCallId));
         parameters.add(new BasicNameValuePair("DialSipResponseCode", "" + statusCode));
         Iterator<String> headerIt = lastResponse.getHeaderNames();
         while (headerIt.hasNext()) {
           String headerName = headerIt.next();
           if (headerName.startsWith("X-")) {
             parameters.add(
                 new BasicNameValuePair(
                     "DialSipHeader_" + headerName, lastResponse.getHeader(headerName)));
           }
         }
       }
     }
   }
   return parameters;
 }
  @Override
  protected void handleReinviteResponse(
      final SIPCallImpl call, final SipServletResponse res, final Map<String, String> headers) {

    if (res.getRequest().getAttribute(SIPCallDelegate.SIPCALL_HOLD_REQUEST) != null
        || res.getRequest().getAttribute(SIPCallDelegate.SIPCALL_UNHOLD_REQUEST) != null
        || res.getRequest().getAttribute(SIPCallDelegate.SIPCALL_DEAF_REQUEST) != null) {
      try {
        res.createAck().send();
        if (call.getHoldState() == HoldState.Holding) {
          call.setHoldState(HoldState.Held);
        } else if (call.getHoldState() == HoldState.UnHolding) {
          call.setHoldState(HoldState.None);
        } else if (call.getDeafState() == HoldState.Deafing) {
          call.setDeafState(HoldState.Deafed);
        } else if (call.getDeafState() == HoldState.Undeafing) {
          call.setDeafState(HoldState.None);
        }
      } catch (IOException e) {
        LOG.error("IOException when sending back ACK.", e);
        call.setHoldState(HoldState.None);
        call.setDeafState(HoldState.None);
        call.fail(e);
      } finally {
        call.notify();
      }
    } else if (res.getRequest().getAttribute(SIPCallDelegate.SIPCALL_MUTE_REQUEST) != null
        || res.getRequest().getAttribute(SIPCallDelegate.SIPCALL_UNMUTE_REQUEST) != null) {
      // send ACK.
      try {
        res.createAck().send();

        // send the received SDP to peer.
        final SIPCallImpl peer = (SIPCallImpl) call.getLastPeer();
        synchronized (peer) {
          if (call.getMuteState() == HoldState.Muting) {
            peer.setDeafState(HoldState.Deafing);
          } else {
            peer.setDeafState(HoldState.Undeafing);
          }

          SipServletRequest reInvite = peer.getSipSession().createRequest("INVITE");
          reInvite.setAttribute(SIPCallDelegate.SIPCALL_DEAF_REQUEST, "true");
          reInvite.setContent(res.getRawContent(), "application/sdp");
          reInvite.send();

          while (peer.getDeafState() != HoldState.Deafed && peer.getDeafState() != HoldState.None) {
            try {
              peer.wait();
            } catch (InterruptedException e) {
              LOG.warn(
                  "InterruptedException when wait make peer deaf, the peer's DeafState "
                      + peer.getDeafState());
            }
          }

          // set call deaf state
          if (call.getMuteState() == HoldState.Muting) {
            peer.setDeafState(HoldState.Deafed);
            call.setMuteState(HoldState.Muted);
          } else if (call.getMuteState() == HoldState.UnMuting) {
            peer.setDeafState(HoldState.None);
            call.setMuteState(HoldState.None);
          }
        }
      } catch (IOException e1) {
        LOG.error("IOException", e1);
        call.setMuteState(HoldState.None);
        call.fail(e1);
      } finally {
        call.notify();
      }
    } else {
      try {
        final SipServletRequest req = res.getRequest();
        final SipServletRequest newReq = (SipServletRequest) SIPHelper.getLinkSIPMessage(req);
        if (newReq != null) {
          SIPHelper.unlinkSIPMessage(req);
          final SipServletResponse newRes =
              newReq.createResponse(res.getStatus(), res.getReasonPhrase());
          SIPHelper.addHeaders(newRes, headers);
          SIPHelper.copyContent(res, newRes);
          if (SIPHelper.isReinvite(newRes)) {
            newRes.getSession().setAttribute(REINVITE_PEER_RES, res);
          }
          newRes.send();
        }
      } catch (final Exception e) {
        LOG.warn("", e);
        return;
      }
    }
  }
  @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();
        }
      }
    }
  }
  @Override
  protected void doInviteResponse(
      final SipServletResponse res, final SIPCallImpl call, final Map<String, String> headers)
      throws Exception {
    try {
      if (_call2.equals(call)) {
        if (SIPHelper.isProvisionalResponse(res)) {
          call.setSIPCallState(SIPCall.State.ANSWERING);

          if (res.getStatus() == SipServletResponse.SC_SESSION_PROGRESS) {
            if (SIPHelper.getRawContentWOException(res) != null) {
              ((SIPOutgoingCall) _call1)
                  .call(res.getRawContent(), _call2.getSipSession().getApplicationSession());
              _invitedCall1 = true;
            }
            try {
              res.createPrack().send();
            } catch (Rel100Exception ex) {
              LOG.warn(ex.getMessage());
            } catch (IllegalStateException ex) {
              LOG.warn(ex.getMessage());
            }
          }
        } else if (SIPHelper.isSuccessResponse(res)) {
          _response = res;
          if (!_invitedCall1) {
            ((SIPOutgoingCall) _call1)
                .call(res.getRawContent(), _call2.getSipSession().getApplicationSession());
          }
        } else if (SIPHelper.isErrorResponse(res)) {
          Exception ex = getExceptionByResponse(res);
          done(getJoinCompleteCauseByResponse(res), ex);
          _call2.disconnect(true, getCallCompleteCauseByResponse(res), ex, null);
        }
      } else if (_call1.equals(call)) {
        if (SIPHelper.isProvisionalResponse(res)) {
          call.setSIPCallState(SIPCall.State.ANSWERING);

          if (res.getStatus() == SipServletResponse.SC_SESSION_PROGRESS) {
            if (SIPHelper.getRawContentWOException(res) != null) {
              SipServletRequest ack2 = null;
              if (_response != null) {
                final SipServletResponse origRes = _response;
                _response = null;
                ack2 = origRes.createAck();
                SIPHelper.copyContent(res, ack2);
              }
              ack2.send();

              _ackedCall2 = true;
            }
            try {
              res.createPrack().send();
            } catch (Rel100Exception ex) {
              LOG.warn("", ex);
            }
          }
        } else if (SIPHelper.isSuccessResponse(res)) {
          final SipServletRequest ack1 = res.createAck();
          ack1.send();

          if (!_ackedCall2) {
            SipServletRequest ack2 = null;
            if (_response != null) {
              final SipServletResponse origRes = _response;
              _response = null;
              ack2 = origRes.createAck();
              SIPHelper.copyContent(res, ack2);
            }
            ack2.send();
          }

          _call2.setSIPCallState(State.ANSWERED);
          _call1.setSIPCallState(State.ANSWERED);
          _call1.linkCall(_call2, JoinType.DIRECT, _direction);
          done(JoinCompleteEvent.Cause.JOINED, null);
        } else if (SIPHelper.isErrorResponse(res)) {
          Exception ex = getExceptionByResponse(res);
          done(getJoinCompleteCauseByResponse(res), ex);
          _call1.disconnect(true, getCallCompleteCauseByResponse(res), ex, null);
          _call2.disconnect(true, getCallCompleteCauseByResponse(res), ex, null);
        }
      }
    } catch (final Exception e) {
      done(JoinCompleteEvent.Cause.ERROR, e);
      _call1.fail(e);
      _call2.fail(e);
      throw e;
    }
  }
示例#25
0
 /** Returns one-line description of the specified response object. */
 private static String getSummary(final SipServletResponse resp) {
   return "" + resp.getStatus() + "/" + resp.getMethod();
 }
示例#26
0
  /**
   * @param response
   * @throws IOException
   */
  public static void forwardResponse(final SipServletResponse response) throws IOException {
    if (logger.isInfoEnabled()) {
      logger.info(String.format("B2BUA: Got response: \n %s", response));
    }
    CallDetailRecordsDao records = daoManager.getCallDetailRecordsDao();

    // container handles CANCEL related responses no need to forward them
    if (response.getStatus() == 487
        || (response.getStatus() == 200 && response.getMethod().equalsIgnoreCase("CANCEL"))) {
      if (logger.isDebugEnabled()) {
        logger.debug("response to CANCEL not forwarding");
      }
      // Update CallDetailRecord
      SipServletRequest request =
          (SipServletRequest) getLinkedSession(response).getAttribute(B2BUA_LAST_REQUEST);
      CallDetailRecord callRecord =
          records.getCallDetailRecord((Sid) request.getSession().getAttribute(CDR_SID));

      if (callRecord != null) {
        logger.info("CDR found! Updating");
        callRecord = callRecord.setStatus(CallStateChanged.State.CANCELED.name());
        final DateTime now = DateTime.now();
        callRecord = callRecord.setEndTime(now);
        final int seconds =
            (int) (DateTime.now().getMillis() - callRecord.getStartTime().getMillis()) / 1000;
        callRecord = callRecord.setDuration(seconds);
        records.updateCallDetailRecord(callRecord);
      }
      return;
    }
    // forward the response
    response.getSession().setAttribute(B2BUA_LAST_RESPONSE, response);
    SipServletRequest request =
        (SipServletRequest) getLinkedSession(response).getAttribute(B2BUA_LAST_REQUEST);
    SipServletResponse resp = request.createResponse(response.getStatus());
    CallDetailRecord callRecord =
        records.getCallDetailRecord((Sid) request.getSession().getAttribute(CDR_SID));

    if (response.getContent() != null) {
      final byte[] sdp = response.getRawContent();
      String offer = null;
      if (response.getContentType().equalsIgnoreCase("application/sdp")) {
        // Issue 306: https://telestax.atlassian.net/browse/RESTCOMM-306
        Registration registration =
            daoManager.getRegistrationsDao().getRegistration(callRecord.getTo());
        final String externalIp = registration.getLocation().split(":")[1].split("@")[1];
        try {
          logger.debug("Got original address from Registration :" + externalIp);
          offer = patch(sdp, externalIp);
        } catch (SdpException e) {
          logger.error("Unexpected exception while patching sdp ", e);
        }
        if (offer != null) {
          resp.setContent(offer, response.getContentType());
        } else {
          resp.setContent(sdp, response.getContentType());
        }
      }
    }
    resp.send();

    //        CallDetailRecord callRecord = records.getCallDetailRecord((Sid)
    // request.getSession().getAttribute(CDR_SID));
    if (callRecord != null) {
      logger.info("CDR found! Updating");
      if (!request.getMethod().equalsIgnoreCase("BYE")) {
        if (response.getStatus() == 100 || response.getStatus() == 180) {
          callRecord = callRecord.setStatus(CallStateChanged.State.RINGING.name());
        } else if (response.getStatus() == 200 || response.getStatus() == 202) {
          callRecord = callRecord.setStatus(CallStateChanged.State.IN_PROGRESS.name());
          callRecord = callRecord.setAnsweredBy(((SipURI) response.getTo().getURI()).getUser());
          final DateTime now = DateTime.now();
          callRecord = callRecord.setStartTime(now);

        } else if (response.getStatus() == 486 || response.getStatus() == 600) {
          callRecord = callRecord.setStatus(CallStateChanged.State.BUSY.name());
        } else if (response.getStatus() > 400) {
          callRecord = callRecord.setStatus(CallStateChanged.State.FAILED.name());
        }
      } else {
        callRecord = callRecord.setStatus(CallStateChanged.State.COMPLETED.name());
        final DateTime now = DateTime.now();
        callRecord = callRecord.setEndTime(now);
        final int seconds =
            (int) ((DateTime.now().getMillis() - callRecord.getStartTime().getMillis()) / 1000);
        callRecord = callRecord.setDuration(seconds);
      }

      records.updateCallDetailRecord(callRecord);
    }
  }
示例#27
0
    @Override
    public void execute(final Object message) throws Exception {
      if (logger.isInfoEnabled()) {
        logger.info("UssdInterpreter Processing INFO request");
      }
      final NotificationsDao notifications = storage.getNotificationsDao();
      SipServletRequest info = (SipServletRequest) message;

      SipServletResponse okay = info.createResponse(200);
      okay.send();

      UssdInfoRequest ussdInfoRequest = new UssdInfoRequest(info);
      String ussdText = ussdInfoRequest.getMessage();
      if (ussdCollectAction != null && !ussdCollectAction.isEmpty() && ussdText != null) {
        URI target = null;
        try {
          target = URI.create(ussdCollectAction);
        } catch (final Exception exception) {
          final Notification notification =
              notification(ERROR_NOTIFICATION, 11100, ussdCollectAction + " is an invalid URI.");
          notifications.addNotification(notification);
          sendMail(notification);
          final StopInterpreter stop = new StopInterpreter();
          source.tell(stop, source);
          return;
        }
        final URI base = request.getUri();
        final URI uri = UriUtils.resolve(base, target);
        // Parse "method".
        String method = "POST";
        Attribute attribute = null;
        try {
          attribute = verb.attribute("method");
        } catch (Exception e) {
        }
        if (attribute != null) {
          method = attribute.value();
          if (method != null && !method.isEmpty()) {
            if (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) {
              final Notification notification =
                  notification(
                      WARNING_NOTIFICATION,
                      14104,
                      method + " is not a valid HTTP method for <Gather>");
              notifications.addNotification(notification);
              method = "POST";
            }
          } else {
            method = "POST";
          }
        }

        final List<NameValuePair> parameters = parameters();
        parameters.add(new BasicNameValuePair("Digits", ussdText));
        request = new HttpRequestDescriptor(uri, method, parameters);
        downloader.tell(request, source);
        ussdCollectTag = null;
        ussdLanguageTag = null;
        ussdMessageTags = new LinkedBlockingQueue<Tag>();
        return;
      } else if (ussdInfoRequest
          .getUssdMessageType()
          .equals(UssdMessageType.unstructuredSSNotify_Response)) {
        UssdRestcommResponse ussdRestcommResponse = new UssdRestcommResponse();
        ussdRestcommResponse.setErrorCode("1");
        ussdRestcommResponse.setIsFinalMessage(true);
        ussdCall.tell(ussdRestcommResponse, source);
        return;
      }
      // Ask the parser for the next action to take.
      final GetNextVerb next = GetNextVerb.instance();
      parser.tell(next, self());
    }