Package javax.sip

Examples of javax.sip.SipException


        // JvB: strictly speaking it is allowed to start a dialog with
        // SUBSCRIBE,
        // then send INVITE+ACK later on
        if (!method.equals(Request.INVITE))
            throw new SipException("Dialog was not created with an INVITE"
                    + method);

        if (cseqno <= 0)
            throw new InvalidArgumentException("bad cseq <= 0 ");
        else if (cseqno > ((((long) 1) << 32) - 1))
            throw new InvalidArgumentException("bad cseq > "
                    + ((((long) 1) << 32) - 1));

        if (this.getRemoteTarget() == null) {
            throw new SipException("Cannot create ACK - no remote Target!");
        }

        if (this.sipStack.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
            this.sipStack.getStackLogger().logDebug(
                    "createAck " + this + " cseqno " + cseqno);
        }

        // MUST ack in the same order that the OKs were received. This traps
        // out of order ACK sending. Old ACKs seqno's can always be ACKed.
        if (lastInviteOkReceived < cseqno) {
            if (sipStack.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
                this.sipStack.getStackLogger().logDebug(
                        "WARNING : Attempt to crete ACK without OK " + this);
                this.sipStack.getStackLogger().logDebug(
                        "LAST RESPONSE = " + this.getLastResponseStatusCode());
            }
            throw new SipException(
                    "Dialog not yet established -- no OK response!");
        }

        try {

            // JvB: Transport from first entry in route set, or remote Contact
            // if none
            // Only used to find correct LP & create correct Via
            SipURI uri4transport = null;

            if (this.routeList != null && !this.routeList.isEmpty()) {
                Route r = (Route) this.routeList.getFirst();
                uri4transport = ((SipURI) r.getAddress().getURI());
            } else { // should be !=null, checked above
                uri4transport = ((SipURI) this.getRemoteTarget().getURI());
            }

            String transport = uri4transport.getTransportParam();
            ListeningPointImpl lp;
            if (transport != null) {
                lp = (ListeningPointImpl) sipProvider
                        .getListeningPoint(transport);
            } else {
                if (uri4transport.isSecure()) { // JvB fix: also support TLS
                    lp = (ListeningPointImpl) sipProvider
                            .getListeningPoint(ListeningPoint.TLS);
                } else {
                    lp = (ListeningPointImpl) sipProvider
                            .getListeningPoint(ListeningPoint.UDP);
                    if (lp == null) { // Alex K fix: let's try to find TCP
                        lp = (ListeningPointImpl) sipProvider
                                .getListeningPoint(ListeningPoint.TCP);
                    }
                }
            }
            if (lp == null) {
                if (sipStack.isLoggingEnabled()) {
                    sipStack.getStackLogger().logError(
                            "remoteTargetURI "
                                    + this.getRemoteTarget().getURI());
                    sipStack.getStackLogger().logError(
                            "uri4transport = " + uri4transport);
                    sipStack.getStackLogger().logError(
                            "No LP found for transport=" + transport);
                }
                throw new SipException(
                        "Cannot create ACK - no ListeningPoint for transport towards next hop found:"
                                + transport);
            }
            SIPRequest sipRequest = new SIPRequest();
            sipRequest.setMethod(Request.ACK);
            sipRequest.setRequestURI((SipUri) getRemoteTarget().getURI()
                    .clone());
            sipRequest.setCallId(this.getCallId());
            sipRequest.setCSeq(new CSeq(cseqno, Request.ACK));
            List<Via> vias = new ArrayList<Via>();
            // Via via = lp.getViaHeader();
            // The user may have touched the sentby for the response.
            // so use the via header extracted from the response for the ACK =>
            // https://jain-sip.dev.java.net/issues/show_bug.cgi?id=205
            // strip the params from the via of the response and use the params
            // from the
            // original request
            Via via = this.lastResponseTopMostVia;
            via.removeParameters();
            if (originalRequest != null
                    && originalRequest.getTopmostVia() != null) {
                NameValueList originalRequestParameters = originalRequest
                        .getTopmostVia().getParameters();
                if (originalRequestParameters != null
                        && originalRequestParameters.size() > 0) {
                    via.setParameters((NameValueList) originalRequestParameters
                            .clone());
                }
            }
            via.setBranch(Utils.getInstance().generateBranchId()); // new branch
            vias.add(via);
            sipRequest.setVia(vias);
            From from = new From();
            from.setAddress(this.getLocalParty());
            from.setTag(this.myTag);
            sipRequest.setFrom(from);
            To to = new To();
            to.setAddress(this.getRemoteParty());
            if (hisTag != null)
                to.setTag(this.hisTag);
            sipRequest.setTo(to);
            sipRequest.setMaxForwards(new MaxForwards(70));

            if (this.originalRequest != null) {
                Authorization authorization = this.originalRequest
                        .getAuthorization();
                if (authorization != null)
                    sipRequest.setHeader(authorization);
                // jeand : setting back the original Request to null to avoid
                // keeping references around for too long
                // since it is used only in the dialog setup
                originalRequestRecordRouteHeaders = originalRequest
                        .getRecordRouteHeaders();
                originalRequest = null;
            }

            // ACKs for 2xx responses
            // use the Route values learned from the Record-Route of the 2xx
            // responses.
            this.updateRequest(sipRequest);

            return sipRequest;
        } catch (Exception ex) {
            InternalErrorHandler.handleException(ex);
            throw new SipException("unexpected exception ", ex);
        }

    }
View Full Code Here


     */
    public Response createReliableProvisionalResponse(int statusCode)
            throws InvalidArgumentException, SipException {

        if (!(firstTransactionIsServerTransaction)) {
            throw new SipException("Not a Server Dialog!");

        }
        /*
         * A UAS MUST NOT attempt to send a 100 (Trying) response reliably. Only
         * provisional responses numbered 101 to 199 may be sent reliably. If
         * the request did not include either a Supported or Require header
         * field indicating this feature, the UAS MUST NOT send the provisional
         * response reliably.
         */
        if (statusCode <= 100 || statusCode > 199)
            throw new InvalidArgumentException("Bad status code ");
        SIPRequest request = this.originalRequest;
        if (!request.getMethod().equals(Request.INVITE))
            throw new SipException("Bad method");

        ListIterator<SIPHeader> list = request.getHeaders(SupportedHeader.NAME);
        if (list == null || !optionPresent(list, "100rel")) {
            list = request.getHeaders(RequireHeader.NAME);
            if (list == null || !optionPresent(list, "100rel")) {
                throw new SipException(
                        "No Supported/Require 100rel header in the request");
            }
        }

        SIPResponse response = request.createResponse(statusCode);
View Full Code Here

     * )
     */
    public void sendReliableProvisionalResponse(Response relResponse)
            throws SipException {
        if (!this.isServer()) {
            throw new SipException("Not a Server Dialog");
        }

        SIPResponse sipResponse = (SIPResponse) relResponse;

        if (relResponse.getStatusCode() == 100)
            throw new SipException(
                    "Cannot send 100 as a reliable provisional response");

        if (relResponse.getStatusCode() / 100 > 2)
            throw new SipException(
                    "Response code is not a 1xx response - should be in the range 101 to 199 ");

        /*
         * Do a little checking on the outgoing response.
         */
        if (sipResponse.getToTag() == null) {
            throw new SipException(
                    "Badly formatted response -- To tag mandatory for Reliable Provisional Response");
        }
        ListIterator requireList = (ListIterator) relResponse
                .getHeaders(RequireHeader.NAME);
        boolean found = false;
View Full Code Here

     *
     * @see javax.sip.SipProvider#sendRequest(javax.sip.message.Request)
     */
    public void sendRequest(Request request) throws SipException {
        if (!sipStack.isAlive())
            throw new SipException("Stack is stopped.");

        // mranga: added check to ensure we are not sending empty (keepalive)
        // message.
        if (((SIPRequest) request).getRequestLine() != null
                && request.getMethod().equals(Request.ACK)) {
            Dialog dialog = sipStack.getDialog(((SIPRequest) request)
                    .getDialogId(false));
            if (dialog != null && dialog.getState() != null) {
              if (sipStack.isLoggingEnabled())
                sipStack.getStackLogger().logWarning(
                        "Dialog exists -- you may want to use Dialog.sendAck() "
                                + dialog.getState());
            }
        }
        Hop hop = sipStack.getRouter((SIPRequest) request).getNextHop(request);
        if (hop == null)
            throw new SipException("could not determine next hop!");
        SIPRequest sipRequest = (SIPRequest) request;
        // Check if we have a valid via.
        // Null request is used to send default proxy keepalive messages.
        if ((!sipRequest.isNullRequest()) && sipRequest.getTopmostVia() == null)
            throw new SipException("Invalid SipRequest -- no via header!");

        try {
            /*
             * JvB: Via branch should already be OK, dont touch it here? Some
             * apps forward statelessly, and then it's not set. So set only when
             * not set already, dont overwrite CANCEL branch here..
             */
            if (!sipRequest.isNullRequest()) {
                Via via = sipRequest.getTopmostVia();
                String branch = via.getBranch();
                if (branch == null || branch.length() == 0) {
                    via.setBranch(sipRequest.getTransactionId());
                }
            }
            MessageChannel messageChannel = null;
            if (this.listeningPoints.containsKey(hop.getTransport()
                    .toUpperCase()))
                messageChannel = sipStack.createRawMessageChannel(
                        this.getListeningPoint(hop.getTransport()).getIPAddress(),
                        this.getListeningPoint(hop.getTransport()).getPort(), hop);
            if (messageChannel != null) {
                messageChannel.sendMessage((SIPMessage) sipRequest,hop);
            } else {
                throw new SipException(
                        "Could not create a message channel for "
                                + hop.toString());
            }
        } catch (IOException ex) {
            if (sipStack.isLoggingEnabled()) {
                sipStack.getStackLogger().logException(ex);
            }

            throw new SipException(
                    "IO Exception occured while Sending Request", ex);

        } catch (ParseException ex1) {
            InternalErrorHandler.handleException(ex1);
        } finally {
View Full Code Here

     *
     * @see javax.sip.SipProvider#sendResponse(javax.sip.message.Response)
     */
    public void sendResponse(Response response) throws SipException {
        if (!sipStack.isAlive())
            throw new SipException("Stack is stopped");
        SIPResponse sipResponse = (SIPResponse) response;
        Via via = sipResponse.getTopmostVia();
        if (via == null)
            throw new SipException("No via header in response!");
        SIPServerTransaction st = (SIPServerTransaction) sipStack.findTransaction((SIPMessage)response, true);
        if ( st != null   && st.getInternalState() != TransactionState._TERMINATED && this.isAutomaticDialogSupportEnabled()) {
            throw new SipException("Transaction exists -- cannot send response statelessly");
        }
        String transport = via.getTransport();

        // check to see if Via has "received paramaeter". If so
        // set the host to the via parameter. Else set it to the
        // Via host.
        String host = via.getReceived();

        if (host == null)
            host = via.getHost();

        // Symmetric nat support
        int port = via.getRPort();
        if (port == -1) {
            port = via.getPort();
            if (port == -1) {
                if (transport.equalsIgnoreCase("TLS"))
                    port = 5061;
                else
                    port = 5060;
            }
        }

        // for correct management of IPv6 addresses.
        if (host.indexOf(":") > 0)
            if (host.indexOf("[") < 0)
                host = "[" + host + "]";

        Hop hop = sipStack.getAddressResolver().resolveAddress(
                new HopImpl(host, port, transport));

        try {
            ListeningPointImpl listeningPoint = (ListeningPointImpl) this
                    .getListeningPoint(transport);
            if (listeningPoint == null)
                throw new SipException(
                        "whoopsa daisy! no listening point found for transport "
                                + transport);
            MessageChannel messageChannel = sipStack.createRawMessageChannel(
                    this.getListeningPoint(hop.getTransport()).getIPAddress(),
                    listeningPoint.port, hop);
            messageChannel.sendMessage(sipResponse);
        } catch (IOException ex) {
            throw new SipException(ex.getMessage());
        }
    }
View Full Code Here

    public Dialog getNewDialog(Transaction transaction) throws SipException {
        if (transaction == null)
            throw new NullPointerException("Null transaction!");

        if (!sipStack.isAlive())
            throw new SipException("Stack is stopped.");

        if (isAutomaticDialogSupportEnabled())
            throw new SipException(" Error - AUTOMATIC_DIALOG_SUPPORT is on");

        if (!sipStack.isDialogCreated(transaction.getRequest().getMethod()))
            throw new SipException("Dialog cannot be created for this method "
                    + transaction.getRequest().getMethod());

        SIPDialog dialog = null;
        SIPTransaction sipTransaction = (SIPTransaction) transaction;

        if (transaction instanceof ServerTransaction) {
            SIPServerTransaction st = (SIPServerTransaction) transaction;
            Response response = st.getLastResponse();
            if (response != null) {
                if (response.getStatusCode() != 100)
                    throw new SipException(
                            "Cannot set dialog after response has been sent");
            }
            SIPRequest sipRequest = (SIPRequest) transaction.getRequest();
            String dialogId = sipRequest.getDialogId(true);
            dialog = sipStack.getDialog(dialogId);
            if (dialog == null) {
                dialog = sipStack.createDialog((SIPTransaction) transaction);
                // create and register the dialog and add the inital route set.
                dialog.addTransaction(sipTransaction);
                dialog.addRoute(sipRequest);
                sipTransaction.setDialog(dialog, null);

            } else {
                sipTransaction.setDialog(dialog, sipRequest.getDialogId(true));
            }
            if (sipRequest.getMethod().equals(Request.INVITE) && this.isDialogErrorsAutomaticallyHandled()) {
                sipStack.putInMergeTable(st, sipRequest);
            }
        } else {

            SIPClientTransaction sipClientTx = (SIPClientTransaction) transaction;

            SIPResponse response = sipClientTx.getLastResponse();

            if (response == null) {
                // A response has not yet been received, then set this up as the
                // default dialog.
                SIPRequest request = (SIPRequest) sipClientTx.getRequest();

                String dialogId = request.getDialogId(false);
                dialog = sipStack.getDialog(dialogId);
                if (dialog != null) {
                    throw new SipException("Dialog already exists!");
                } else {
                    dialog = sipStack.createDialog(sipTransaction);
                }
                sipClientTx.setDialog(dialog, null);

            } else {
                throw new SipException(
                        "Cannot call this method after response is received!");
            }
        }
        dialog.addEventListener(this);
        return dialog;
View Full Code Here

            throw new NullPointerException("null response");

        try {
            sipResponse.checkHeaders();
        } catch (ParseException ex) {
            throw new SipException(ex.getMessage());
        }

        // check for meaningful response.
        final String responseMethod = sipResponse.getCSeq().getMethod();
        if (!responseMethod.equals(this.getMethod())) {
            throw new SipException(
                    "CSeq method does not match Request method of request that created the tx.");
        }

        /*
         * 200-class responses to SUBSCRIBE requests also MUST contain an "Expires" header. The
         * period of time in the response MAY be shorter but MUST NOT be longer than specified in
         * the request.
         */
        final int statusCode = response.getStatusCode();
        if (this.getMethod().equals(Request.SUBSCRIBE) && statusCode / 100 == 2) {

            if (response.getHeader(ExpiresHeader.NAME) == null) {
                throw new SipException("Expires header is mandatory in 2xx response of SUBSCRIBE");
            } else {
                Expires requestExpires = (Expires) this.getOriginalRequest().getExpires();
                Expires responseExpires = (Expires) response.getExpires();
                /*
                 * If no "Expires" header is present in a SUBSCRIBE request, the implied default
                 * is defined by the event package being used.
                 */
                if (requestExpires != null
                        && responseExpires.getExpires() > requestExpires.getExpires()) {
                    throw new SipException(
                            "Response Expires time exceeds request Expires time : See RFC 3265 3.1.1");
                }
            }

        }

        // Check for mandatory header.
        if (statusCode == 200
                && responseMethod.equals(Request.INVITE)
                && sipResponse.getHeader(ContactHeader.NAME) == null)
            throw new SipException("Contact Header is mandatory for the OK to the INVITE");

        if (!this.isMessagePartOfTransaction((SIPMessage) response)) {
            throw new SipException("Response does not belong to this transaction.");
        }

        // Fix up the response if the dialog has already been established.
        try {
            /*
             * The UAS MAY send a final response to the initial request before
             * having received PRACKs for all unacknowledged reliable provisional responses,
             * unless the final response is 2xx and any of the unacknowledged reliable provisional
             * responses contained a session description. In that case, it MUST NOT send a final
             * response until those provisional responses are acknowledged.
             */
          final ContentTypeHeader contentTypeHeader = ((SIPResponse)response).getContentTypeHeader();
            if (this.pendingReliableResponseAsBytes != null
                    && this.getDialog() != null
                    && this.getInternalState() != TransactionState._TERMINATED
                    && statusCode / 100 == 2
                    && contentTypeHeader != null                    
                    && contentTypeHeader.getContentType()
                            .equalsIgnoreCase(CONTENT_TYPE_APPLICATION)
                    && contentTypeHeader.getContentSubType()
                            .equalsIgnoreCase(CONTENT_SUBTYPE_SDP)) {
                if (!interlockProvisionalResponses ) {
                    throw new SipException("cannot send response -- unacked povisional");
                } else {           
                    try {
                       boolean acquired = this.provisionalResponseSem.tryAcquire(1,TimeUnit.SECONDS);
                       if (!acquired ) {
                           throw new SipException("cannot send response -- unacked povisional");
                       }
                    } catch (InterruptedException ex) {
                        sipStack.getStackLogger().logError ("Interrupted acuqiring PRACK sem");
                        throw new SipException("Cannot aquire PRACK sem");
                    }
                 
                }
            } else {
                // Sending the final response cancels the
                // pending response task.
                if (this.pendingReliableResponseAsBytes != null && sipResponse.isFinalResponse()) {
                  sipStack.getTimer().cancel(provisionalResponseTask);                  
                    this.provisionalResponseTask = null;
                }
            }

            // Dialog checks. These make sure that the response
            // being sent makes sense.
            if (dialog != null) {
                if (statusCode / 100 == 2
                        && sipStack.isDialogCreated(responseMethod)) {
                    if (dialog.getLocalTag() == null && sipResponse.getToTag() == null) {
                        // Trying to send final response and user forgot to set
                        // to
                        // tag on the response -- be nice and assign the tag for
                        // the user.
                        sipResponse.getTo().setTag(Utils.getInstance().generateTag());
                    } else if (dialog.getLocalTag() != null && sipResponse.getToTag() == null) {
                      if ( sipStack.getStackLogger().isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
                        sipStack.getStackLogger().logDebug("assigning toTag : serverTransaction = " + this + " dialog "
                            + dialog + " tag = " + dialog.getLocalTag());
                      }
                        sipResponse.setToTag(dialog.getLocalTag());
                    } else if (dialog.getLocalTag() != null && sipResponse.getToTag() != null
                            && !dialog.getLocalTag().equals(sipResponse.getToTag())) {
                        throw new SipException("Tag mismatch dialogTag is "
                                + dialog.getLocalTag() + " responseTag is "
                                + sipResponse.getToTag());
                    }
                }

                if (!sipResponse.getCallId().getCallId().equals(dialog.getCallId().getCallId())) {
                    throw new SipException("Dialog mismatch!");
                }
            }



            // Backward compatibility slippery slope....
            // Only set the from tag in the response when the
            // incoming request has a from tag.
            String fromTag = originalRequestFromTag;
            if(getRequest() != null) {
              fromTag = ((SIPRequest) this.getRequest()).getFromTag();
            }
            if (fromTag != null && sipResponse.getFromTag() != null
                    && !sipResponse.getFromTag().equals(fromTag)) {
                throw new SipException("From tag of request does not match response from tag");
            } else if (fromTag != null) {
                sipResponse.getFrom().setTag(fromTag);
            } else {
                if (sipStack.isLoggingEnabled(LogWriter.TRACE_DEBUG))
                    sipStack.getStackLogger().logDebug("WARNING -- Null From tag in request!!");
            }



            // See if the dialog needs to be inserted into the dialog table
            // or if the state of the dialog needs to be changed.
            if (dialog != null && statusCode != 100) {
                dialog.setResponseTags(sipResponse);
                DialogState oldState = dialog.getState();
                dialog.setLastResponse(this, (SIPResponse) response);
                if (oldState == null && dialog.getState() == DialogState.TERMINATED) {
                    DialogTerminatedEvent event = new DialogTerminatedEvent(dialog
                            .getSipProvider(), dialog);

                    // Provide notification to the listener that the dialog has
                    // ended.
                    dialog.getSipProvider().handleEvent(event, this);

                }

            } else if (dialog == null && this.getMethod().equals(Request.INVITE)
                    && this.retransmissionAlertEnabled
                    && this.retransmissionAlertTimerTask == null
                    && response.getStatusCode() / 100 == 2) {
                String dialogId = ((SIPResponse) response).getDialogId(true);

                this.retransmissionAlertTimerTask = new RetransmissionAlertTimerTask(dialogId);
                sipStack.retransmissionAlertTransactions.put(dialogId, this);
                sipStack.getTimer().scheduleWithFixedDelay(this.retransmissionAlertTimerTask, 0,
                        SIPTransactionStack.BASE_TIMER_INTERVAL);

            }

            // Send message after possibly inserting the Dialog
            // into the dialog table to avoid a possible race condition.

            this.sendMessage((SIPResponse) response);
           
            if ( dialog != null ) {
                dialog.startRetransmitTimer(this, (SIPResponse)response);
            }

        } catch (IOException ex) {
            if (sipStack.isLoggingEnabled())
                sipStack.getStackLogger().logException(ex);
            this.setState(TransactionState._TERMINATED);
            raiseErrorEvent(SIPTransactionErrorEvent.TRANSPORT_ERROR);
            throw new SipException(ex.getMessage());
        } catch (java.text.ParseException ex1) {
            if (sipStack.isLoggingEnabled())
                sipStack.getStackLogger().logException(ex1);
            this.setState(TransactionState._TERMINATED);
            throw new SipException(ex1.getMessage());
        }
    }
View Full Code Here

         * After the first reliable provisional response for a request has been acknowledged, the
         * UAS MAY send additional reliable provisional responses. The UAS MUST NOT send a second
         * reliable provisional response until the first is acknowledged.
         */
        if (this.pendingReliableResponseAsBytes != null) {
            throw new SipException("Unacknowledged response");

        } else {
          SIPResponse reliableResponse = (SIPResponse) relResponse;
            this.pendingReliableResponseAsBytes = reliableResponse.encodeAsBytes(this.getTransport());
            this.pendingReliableResponseMethod = reliableResponse.getCSeq().getMethod();
            this.pendingReliableCSeqNumber = reliableResponse.getCSeq().getSeqNumber();                                   
        }
        /*
         * In addition, it MUST contain a Require header field containing the option tag 100rel,
         * and MUST include an RSeq header field.
         */
        RSeq rseq = (RSeq) relResponse.getHeader(RSeqHeader.NAME);
        if (relResponse.getHeader(RSeqHeader.NAME) == null) {
            rseq = new RSeq();
            relResponse.setHeader(rseq);           
        }

        try {
          if(rseqNumber < 0) {
            this.rseqNumber = (int) (Math.random() * 1000);
          }
            this.rseqNumber++;
            rseq.setSeqNumber(this.rseqNumber);
            this.pendingReliableRSeqNumber = rseq.getSeqNumber();

            // start the timer task which will retransmit the reliable response
            // until the PRACK is received. Cannot send a second provisional.
            this.lastResponse = (SIPResponse) relResponse;
            if ( this.getDialog() != null  && interlockProvisionalResponses ) {
                boolean acquired = this.provisionalResponseSem.tryAcquire(1, TimeUnit.SECONDS);
                if (!acquired) {
                    throw new SipException("Unacknowledged reliable response");
                }
            }
            //moved the task scheduling before the sending of the message to overcome
            // Issue 265 : https://jain-sip.dev.java.net/issues/show_bug.cgi?id=265
            this.provisionalResponseTask = new ProvisionalResponseTask();
View Full Code Here

     * @see javax.sip.ServerTransaction#enableRetransmissionAlerts()
     */

    public void enableRetransmissionAlerts() throws SipException {
        if (this.getDialog() != null)
            throw new SipException("Dialog associated with tx");

        else if (!this.getMethod().equals(Request.INVITE))
            throw new SipException("Request Method must be INVITE");

        this.retransmissionAlertEnabled = true;

    }
View Full Code Here

            // Bug report - Fredrik Wickstrom
            CSeqHeader cSeq = (CSeqHeader) reoriginatedRequest.getHeader((CSeqHeader.NAME));
            try {
                cSeq.setSeqNumber(cSeq.getSeqNumber() + 1l);
            } catch (InvalidArgumentException ex) {
                throw new SipException("Invalid CSeq -- could not increment : "
                        + cSeq.getSeqNumber());
            }


            /* Resolve this to the next hop based on the previous lookup. If we are not using
             * lose routing (RFC2543) then just attach hop as a maddr param.
             */
            if ( challengedRequest.getRouteHeaders() == null ) {
                Hop hop   = ((SIPClientTransaction) challengedTransaction).getNextHop();
                SipURI sipUri = (SipURI) reoriginatedRequest.getRequestURI();
                sipUri.setMAddrParam(hop.getHost());
                if ( hop.getPort() != -1 ) sipUri.setPort(hop.getPort());
            }
            ClientTransaction retryTran = transactionCreator
            .getNewClientTransaction(reoriginatedRequest);

            WWWAuthenticateHeader authHeader = null;
            SipURI requestUri = (SipURI) challengedTransaction.getRequest().getRequestURI();
            while (authHeaders.hasNext()) {
                authHeader = (WWWAuthenticateHeader) authHeaders.next();
                String realm = authHeader.getRealm();
                AuthorizationHeader authorization = null;
                String sipDomain;
                if ( this.accountManager instanceof SecureAccountManager ) {
                    UserCredentialHash credHash =
                        ((SecureAccountManager)this.accountManager).getCredentialHash(challengedTransaction,realm);
                    if ( credHash == null ) {
                        sipStack.getStackLogger().logDebug("Could not find creds");
                        throw new SipException(
                        "Cannot find user creds for the given user name and realm");
                    }
                    URI uri = reoriginatedRequest.getRequestURI();
                    sipDomain = credHash.getSipDomain();
                    authorization = this.getAuthorization(reoriginatedRequest
                            .getMethod(), uri.toString(),
                            (reoriginatedRequest.getContent() == null) ? "" : new String(
                            reoriginatedRequest.getRawContent()), authHeader, credHash);
                } else {
                    UserCredentials userCreds = ((AccountManager) this.accountManager).getCredentials(challengedTransaction, realm);
                   
                     if (userCreds == null) {
                         throw new SipException(
                            "Cannot find user creds for the given user name and realm");
                     }
                     sipDomain = userCreds.getSipDomain();
                    
                    // we haven't yet authenticated this realm since we were
                    // started.

                       authorization = this.getAuthorization(reoriginatedRequest
                                .getMethod(), reoriginatedRequest.getRequestURI().toString(),
                                (reoriginatedRequest.getContent() == null) ? "" : new String(
                                reoriginatedRequest.getRawContent()), authHeader, userCreds);
                }
               
                if ( sipStack.getStackLogger().isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
                    sipStack.getStackLogger().logDebug(
                            "Created authorization header: " + authorization.toString());
                }
             

                if (cacheTime != 0) {
                    String callId = challengedRequest.getCallId().getCallId();
                    cachedCredentials.cacheAuthorizationHeader(callId,
                            authorization, cacheTime);
                }
                reoriginatedRequest.addHeader(authorization);
            }

          
            if ( sipStack.getStackLogger().isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
                sipStack.getStackLogger().logDebug(
                        "Returning authorization transaction." + retryTran);
            }
         
            return retryTran;
        } catch (SipException ex) {
            throw ex;
        } catch (Exception ex) {
            sipStack.getStackLogger().logError("Unexpected exception ", ex);
            throw new SipException("Unexpected exception ", ex);
        }
    }
View Full Code Here

TOP

Related Classes of javax.sip.SipException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.