/**
   * Gets invoked by the parser as a callback on successful message parsing (i.e. no parser errors).
   *
   * @param sipMessage Mesage to process (this calls the application for processing the message).
   */
  public void processMessage(SIPMessage sipMessage) throws Exception {
    try {
      if (sipMessage.getFrom() == null
          || // sipMessage.getFrom().getTag() == null ||
          sipMessage.getTo() == null
          || sipMessage.getCallId() == null
          || sipMessage.getCSeq() == null
          || sipMessage.getViaHeaders() == null) {
        String badmsg = sipMessage.encode();
        if (LogWriter.needsLogging) {
          stack.logWriter.logMessage("bad message " + badmsg);
          stack.logWriter.logMessage(">>> Dropped Bad Msg");
        }
        stack.logBadMessage(badmsg);
        return;
      }

      ViaList viaList = sipMessage.getViaHeaders();
      // For a request
      // first via header tells where the message is coming from.
      // For response, this has already been recorded in the outgoing
      // message.
      if (sipMessage instanceof SIPRequest) {
        Via v = (Via) viaList.first();
        if (v.hasPort()) {
          this.peerPort = v.getPort();
        } else this.peerPort = 5061;
        this.peerProtocol = v.getTransport();
        try {
          this.peerAddress = mySock.getInetAddress();
          // Check to see if the received parameter matches
          // the peer address and tag it appropriately.
          // Bug fix by [email protected]
          // Should record host address not host name
          // bug fix by  Joost Yervante Damand
          if (!v.getSentBy().getInetAddress().equals(this.peerAddress)) {
            v.setParameter(Via.RECEIVED, this.peerAddress.getHostAddress());
            // @@@ hagai
            v.setParameter(Via.RPORT, new Integer(this.peerPort).toString());
          }
        } catch (java.net.UnknownHostException ex) {
          // Could not resolve the sender address.
          if (LogWriter.needsLogging) {
            stack.logWriter.logMessage("Rejecting message -- could not resolve Via Address");
          }
          return;
        } catch (java.text.ParseException ex) {
          InternalErrorHandler.handleException(ex);
        }
        // Use this for outgoing messages as well.
        if (!this.isCached) {
          ((TLSMessageProcessor) this.messageProcessor).cacheMessageChannel(this);
          this.isCached = true;
          String key = IOHandler.makeKey(mySock.getInetAddress(), this.peerPort);
          stack.ioHandler.putSocket(key, mySock);
        }
      }

      // Foreach part of the request header, fetch it and process it

      long receptionTime = System.currentTimeMillis();
      //

      if (sipMessage instanceof SIPRequest) {
        // This is a request - process the request.
        SIPRequest sipRequest = (SIPRequest) sipMessage;
        // Create a new sever side request processor for this
        // message and let it handle the rest.

        if (LogWriter.needsLogging) {
          stack.logWriter.logMessage("----Processing Message---");
        }

        // Check for reasonable size - reject message
        // if it is too long.
        if (stack.getMaxMessageSize() > 0
            && sipRequest.getSize()
                    + (sipRequest.getContentLength() == null
                        ? 0
                        : sipRequest.getContentLength().getContentLength())
                > stack.getMaxMessageSize()) {
          SIPResponse sipResponse = sipRequest.createResponse(SIPResponse.MESSAGE_TOO_LARGE);
          byte[] resp = sipResponse.encodeAsBytes();
          this.sendMessage(resp, false);
          throw new Exception("Message size exceeded");
        }

        ServerRequestInterface sipServerRequest = stack.newSIPServerRequest(sipRequest, this);
        sipServerRequest.processRequest(sipRequest, this);
        if (this.stack.serverLog.needsLogging(ServerLog.TRACE_MESSAGES)) {
          if (sipServerRequest.getProcessingInfo() == null) {
            stack.serverLog.logMessage(
                sipMessage,
                sipRequest.getViaHost() + ":" + sipRequest.getViaPort(),
                stack.getHostAddress() + ":" + stack.getPort(this.getTransport()),
                false,
                receptionTime);
          } else {
            this.stack.serverLog.logMessage(
                sipMessage,
                sipRequest.getViaHost() + ":" + sipRequest.getViaPort(),
                stack.getHostAddress() + ":" + stack.getPort(this.getTransport()),
                sipServerRequest.getProcessingInfo(),
                false,
                receptionTime);
          }
        }
      } else {
        SIPResponse sipResponse = (SIPResponse) sipMessage;
        // This is a response message - process it.
        // Check the size of the response.
        // If it is too large dump it silently.
        if (stack.getMaxMessageSize() > 0
            && sipResponse.getSize()
                    + (sipResponse.getContentLength() == null
                        ? 0
                        : sipResponse.getContentLength().getContentLength())
                > stack.getMaxMessageSize()) {
          if (LogWriter.needsLogging) this.stack.logWriter.logMessage("Message size exceeded");
          return;
        }
        ServerResponseInterface sipServerResponse = stack.newSIPServerResponse(sipResponse, this);
        sipServerResponse.processResponse(sipResponse, this);
      }
    } finally {
    }
  }
  /**
   * Actually proces the parsed message.
   *
   * @param sipMessage
   */
  public void processMessage(SIPMessage sipMessage) {

    if (sipMessage instanceof SIPRequest) {
      SIPRequest sipRequest = (SIPRequest) sipMessage;

      // This is a request - process it.
      // So far so good -- we will commit this message if
      // all processing is OK.
      if (sipStack.logWriter.isLoggingEnabled(ServerLog.TRACE_MESSAGES)) {

        this.sipStack.serverLog.logMessage(
            sipMessage,
            this.getPeerHostPort().toString(),
            this.getHost() + ":" + this.myPort,
            false,
            receptionTime);
      }
      ServerRequestInterface sipServerRequest = sipStack.newSIPServerRequest(sipRequest, this);
      // Drop it if there is no request returned
      if (sipServerRequest == null) {
        if (sipStack.isLoggingEnabled()) {
          this.sipStack.logWriter.logWarning("Null request interface returned -- dropping request");
        }

        return;
      }
      if (sipStack.isLoggingEnabled())
        this.sipStack.logWriter.logDebug(
            "About to process " + sipRequest.getFirstLine() + "/" + sipServerRequest);
      try {
        sipServerRequest.processRequest(sipRequest, this);
      } finally {
        if (sipServerRequest instanceof SIPTransaction) {
          SIPServerTransaction sipServerTx = (SIPServerTransaction) sipServerRequest;
          if (!sipServerTx.passToListener()) {
            ((SIPTransaction) sipServerRequest).releaseSem();
          }
        }
      }
      if (sipStack.isLoggingEnabled())
        this.sipStack.logWriter.logDebug(
            "Done processing " + sipRequest.getFirstLine() + "/" + sipServerRequest);

      // So far so good -- we will commit this message if
      // all processing is OK.

    } else {
      // Handle a SIP Reply message.
      SIPResponse sipResponse = (SIPResponse) sipMessage;
      try {
        sipResponse.checkHeaders();
      } catch (ParseException ex) {
        if (sipStack.isLoggingEnabled())
          sipStack.logWriter.logError(
              "Dropping Badly formatted response message >>> " + sipResponse);
        return;
      }
      ServerResponseInterface sipServerResponse = sipStack.newSIPServerResponse(sipResponse, this);
      if (sipServerResponse != null) {
        try {
          if (sipServerResponse instanceof SIPClientTransaction
              && !((SIPClientTransaction) sipServerResponse).checkFromTag(sipResponse)) {
            if (sipStack.isLoggingEnabled())
              sipStack.logWriter.logError(
                  "Dropping response message with invalid tag >>> " + sipResponse);
            return;
          }

          sipServerResponse.processResponse(sipResponse, this);
        } finally {
          if (sipServerResponse instanceof SIPTransaction
              && !((SIPTransaction) sipServerResponse).passToListener())
            ((SIPTransaction) sipServerResponse).releaseSem();
        }

        // Normal processing of message.
      } else {
        if (sipStack.isLoggingEnabled()) {
          this.sipStack.logWriter.logDebug("null sipServerResponse!");
        }
      }
    }
  }