Beispiel #1
0
  public boolean sendEventSync(final Event event) {
    boolean succesfull = false;
    if (EchoProtocolManager.getInstance().getMyStation().isActive()) {
      try {
        // Creates a broadcast Datagram Connection
        dgConnection =
            (DatagramConnection)
                Connector.open(
                    "radiogram://"
                        + EchoProtocolManager.getInstance().getMyStation().getAddress().longValue()
                        + ":"
                        + DTSPORT);

        // Creates a Datagram using the above Connection
        final Datagram datagram = dgConnection.newDatagram(dgConnection.getMaximumLength());

        // Clean the Datagram
        datagram.reset();

        // Convert event to byte Array
        final byte[] eventArray = event.toByteArray();

        // Send Class Type
        datagram.writeUTF(event.getClass().getName());

        // Send length
        datagram.writeInt(eventArray.length);

        // Send array
        datagram.write(eventArray, 0, eventArray.length);

        // Send the datagram
        dgConnection.send(datagram);

        dgConnection.close();

        Logger.getInstance().debug("Event sent succefully");
        succesfull = true;

      } catch (Exception ex) {
        Logger.getInstance().debug("Unable to send event", ex);

        // Close the open connection
        try {
          dgConnection.close();
        } catch (Exception e) {
          // eat it
        }

        succesfull = false;
      }
    }
    return succesfull;
  }
  /** Run method specified by runnable. */
  public void run() {

    while (true) {
      // Create a new string message parser to parse the list of messages.
      if (myParser == null) {
        myParser = new StringMsgParser();
        myParser.setParseExceptionListener(this);
      }

      // messages that we write out to the peer.
      Datagram packet;

      if (stack.threadPoolSize != -1) {
        synchronized (((UDPMessageProcessor) messageProcessor).messageQueue) {
          while (((UDPMessageProcessor) messageProcessor).messageQueue.isEmpty()) {

            // Check to see if we need to exit.
            if (!((UDPMessageProcessor) messageProcessor).running) return;

            try {
              // Wait for packets
              ((UDPMessageProcessor) messageProcessor).messageQueue.wait();
            } catch (InterruptedException ex) {
              if (!((UDPMessageProcessor) messageProcessor).running) return;
            }
          }
          packet = (Datagram) ((UDPMessageProcessor) messageProcessor).messageQueue.firstElement();
          ((UDPMessageProcessor) messageProcessor).messageQueue.removeElementAt(0);
        }
        incomingPacket = packet;
      } else {
        packet = incomingPacket;
      }

      if (LogWriter.needsLogging) {
        LogWriter.logMessage(
            LogWriter.TRACE_DEBUG, "Processing new incoming datagram " + packet.getLength());
      }
      // Process the packet. Catch and log any exception we may throw.
      try {
        processIncomingDataPacket(packet);
      } catch (Throwable e) {
        if (LogWriter.needsLogging) {
          LogWriter.logMessage(
              LogWriter.TRACE_EXCEPTION, "Exception processing incoming UDP packet");
          LogWriter.logException((Exception) e);
        }
      }

      if (stack.threadPoolSize == -1) {
        return;
      }
    }
  }
  /**
   * Task execution code: <br>
   * ---------- <br>
   * Performed operations: <br>
   *
   * <ul type="disc">
   *   <li>Add alarm to position strings, if necessary;
   *   <li>Send string;
   *   <li>Check the number of sent strings.
   * </ul>
   */
  public void run() {

    list = new BCListenerCustom();
    list.addInfoStato(infoS);
    BearerControl.addListener(list);

    while (!infoS.isCloseUDPSocketTask()) {

      // if(false){
      if ((infoS.getInfoFileString(TrkState).equals("ON")
              || (infoS.getInfoFileString(TrkState)).equalsIgnoreCase("ON,FMS"))
          && infoS.getInfoFileString(GPRSProtocol).equals("UDP")
          && ((infoS.getInfoFileInt(TrkIN) != infoS.getInfoFileInt(TrkOUT))
              || !infoS.getDataRAM().equals(""))) {

        exitTRKON = false;

        try {

          // Indicates if GPRS SOCKET is ACTIVE
          // System.out.println("TT*UDPSocketTask: START");
          infoS.setIfsocketAttivo(true);
          destAddressUDP =
              "datagram://"
                  + infoS.getInfoFileString(DestHost)
                  + ":"
                  + infoS.getInfoFileString(DestPort);

          /*
           * Once this task has been started, it is completely
           * finished before proceeding to a re-use, even if the
           * timeout expires (so there may be a FIX GPRS timeout
           * expired!)
           */
          try {
            try {
              while (!InfoStato.getCoda()) Thread.sleep(1L);
            } catch (InterruptedException e) {
            }

            if (infoS.getInfoFileInt(TrkIN) == infoS.getInfoFileInt(TrkOUT)) {
              outText = infoS.getDataRAM();
              ram = true;
            } else {
              ram = false;
              temp = infoS.getInfoFileInt("TrkOUT");
              System.out.println("TT*UDPSocketTask: pointer out - " + temp);
              if ((temp >= codaSize) || (temp < 0)) temp = 0;
              outText = infoS.getRecord(temp);
              new LogError("TT*UDPSocketTask: pointer out - " + temp + " " + outText);
              System.out.println("TT*UDPSocketTask: data in queue: " + outText);
            }

            System.out.println("TT*UDPSocketTask: string to send through GPRS:\r\n" + this.outText);

            ctrlSpeed = infoS.getSpeedForTrk();
            if (debug_speed) {
              ctrlSpeed = infoS.getSpeedGree();
              System.out.println("SPEED " + ctrlSpeed);
            }
            try {
              val_insensibgps = Integer.parseInt(infoS.getInfoFileString(InsensibilitaGPS));
            } catch (NumberFormatException e) {
              val_insensibgps = 0;
            }
            // new LogError("Actual speed: " + ctrlSpeed + ". Val insens: " + val_insensibgps);

            if (ram) {

              // System.out.println("ACTUAL SPEED: " + this.ctrlSpeed);
              // System.out.println("outText.indexOf(ALARM) " + (this.outText.indexOf("ALARM") >
              // 0));
              // System.out.println("outText.indexOf(ALIVE) " + (this.outText.indexOf("ALIVE") >
              // 0));
              // System.out.println("SPEED LIMIT: " + this.val_insensibgps);
              // System.out.println("PREVIOUS MESSAGE IS ALIVE: " + this.infoS.getPreAlive());
              // System.out.println("SPEED LIMIT: " + this.val_insensibgps);
              // System.out.println("PREVIOUS SPEED: " + this.infoS.getPreSpeedDFS());

              if (this.ctrlSpeed > this.val_insensibgps) {
                System.out.println("Speed check ok.");
                infoS.settrasmetti(true);
                if (this.infoS.getInvioStop()) {
                  infoS.setApriGPRS(true);
                }
                infoS.setInvioStop(false);
              } else {
                if ((outText.indexOf("ALARM") > 0) || (outText.indexOf("ALIVE") > 0)) {
                  System.out.println("Alarm");
                  infoS.settrasmetti(true);
                  infoS.setApriGPRS(true);
                } else {

                  if ((!infoS.getPreAlive())
                      && (ctrlSpeed <= val_insensibgps)
                      && (infoS.getPreSpeedDFS() > val_insensibgps)) {

                    System.out.println(
                        "Speed check less then insensitivity, previous speed is greater");
                    infoS.settrasmetti(true);
                    if (infoS.getInvioStop() == true) {
                      infoS.setApriGPRS(true);
                    }
                    infoS.setInvioStop(false);

                  } else {

                    System.out.println("Speed check failed.");
                    if (infoS.getInvioStop() == false) {
                      System.out.println("Send stop coordinate.");
                      infoS.settrasmetti(true);
                      infoS.setInvioStop(true);
                      infoS.setChiudiGPRS(true);

                      // new LogError("Send stop.");
                    }
                  }
                }
              }
              if (this.outText.indexOf("ALIVE") > 0) {
                System.out.println("ALIVE MESSAGE");
                infoS.setPreAlive(true);
              } else {
                infoS.setPreAlive(false);
                System.out.println("NO ALIVE MESSAGE");
              }
            } else {
              // new LogError("From store.");

              infoS.settrasmetti(true);

              infoS.setChiudiGPRS(false);
            }

            // new LogError("Transmission status: " + infoS.gettrasmetti());

            if (infoS.gettrasmetti() == true) {

              infoS.settrasmetti(false);

              if (infoS.getApriGPRS() == true) {

                close = false;
                infoS.setTRKstate(true);
                try {
                  semAT.getCoin(5);
                  infoS.setATexec(true);
                  mbox2.write("at^smong\r");
                  while (infoS.getATexec()) {
                    Thread.sleep(whileSleep);
                  }
                  infoS.setATexec(true);
                  mbox2.write("at+cgatt=1\r");
                  while (infoS.getATexec()) {
                    Thread.sleep(whileSleep);
                  }
                  semAT.putCoin();
                } catch (Exception e) {
                }

                // Open GPRS Channel
                try {
                  udpConn = (UDPDatagramConnection) Connector.open(destAddressUDP);
                } catch (Exception e) {
                  System.out.println("TT*UDPSocketTask: Connector.open");
                }
                infoS.setApriGPRS(false);
              }

              try {
                // mem2 = r.freeMemory();
                // System.out.println("Free memory after allocation: " + mem2);
                if ((outText == null) || (outText.indexOf("null") >= 0)) {
                  outText =
                      infoS.getInfoFileString(Header)
                          + ","
                          + infoS.getInfoFileString(IDtraker)
                          + defaultGPS
                          + ",<ERROR>*00";
                  buff = outText.getBytes();
                }
                System.out.println("OPEN DATAGRAM");
                System.out.println(outText);
                dgram = udpConn.newDatagram(outText.length());
                buff = new byte[outText.length()];
                System.out.println("SEND DATAGRAM");
                buff = outText.getBytes();
                new LogError("outText = " + outText);
                dgram.setData(buff, 0, buff.length);
                udpConn.send(dgram);
                int gprsCount = 0;
                answer = "";
                String ack = infoS.getInfoFileString(Ackn);
                if (!infoS.getInfoFileString(Ackn).equals("")) {
                  while (true) {
                    dgram.reset();
                    dgram.setLength(infoS.getInfoFileString(Ackn).length() + 1);
                    udpConn.receive(dgram);
                    byte[] data = dgram.getData();
                    answer = new String(data);
                    answer = answer.substring(0, ack.length());
                    if (debug) {
                      System.out.println("ACK: " + answer);
                    }
                    if (answer.equals(ack)) {
                      new LogError("ACK");
                      if (debug) System.out.println("ACK RECEIVED");
                      break;
                    } else {
                      if (debug) System.out.println("WAITING ACK");
                      try {
                        Thread.sleep(1000);
                      } catch (InterruptedException e) {
                      }
                      gprsCount++;
                    }
                    if (gprsCount > 15) {
                      new LogError("NACK");
                      infoS.setReboot();
                      errorSent = true;
                      break;
                    }
                  }
                }

              } catch (Exception err) {
                System.out.println("TT*UDPSocketTask: Exception err");
                new LogError("TT*UDPSocketTask: Exception during out text" + err.getMessage());
                infoS.setReboot();
                errorSent = true;
                break;
              }
              // new LogError(outText);
              if (debug) System.out.println(outText);

              if (infoS.getChiudiGPRS() == true) {

                infoS.setTRKstate(false);
                try {
                  System.out.println("TT*UDPSocketTask: close UDP");
                  udpConn.close();
                } catch (NullPointerException e) {
                  infoS.setChiudiGPRS(false);
                }
                infoS.setChiudiGPRS(false);
              }
            }

            System.out.println("BEARER: " + infoS.getGprsState());
            if (!infoS.getGprsState()) {
              errorSent = true;
              System.out.println("BEARER ERROR");
              new LogError("BEARER ERROR");
            }

            if (ram) {
              if (!errorSent) {
                infoS.setDataRAM("");
              }
            } else {
              if (!errorSent) {
                temp++;
                if (temp >= codaSize || temp < 0) temp = 0;
                infoS.setInfoFileInt(TrkOUT, "" + temp);
                file.setImpostazione(TrkOUT, "" + temp);
                InfoStato.getFile();
                file.writeSettings();
                InfoStato.freeFile();
              }
              errorSent = false;
            }
            InfoStato.freeCoda();

            infoS.setIfsocketAttivo(false);
            Thread.sleep(100);
            if (errorSent) {
              close = true;
              semAT.putCoin(); // release AT interface
              infoS.setIfsocketAttivo(false);
              infoS.setApriGPRS(false);
              infoS.setChiudiGPRS(false);
            }
            // r.gc(); // request garbage collection

            // mem2 = r.freeMemory();
            // System.out.println("Free memory after collecting" + " discarded Integers: " + mem2);

          } catch (IOException e) {
            close = true;
            String msgExcept = e.getMessage();
            System.out.println("TT*UDPSocketTask: exception: " + msgExcept);

            // new LogError("SocketGPRStask IOException: " + e);
            infoS.setIfsocketAttivo(false);

            infoS.setApriGPRS(false);
            infoS.setChiudiGPRS(false);

          } catch (EmptyStackException e) {
            close = true;
            // System.out.println("exception: " + e.getMessage());
            e.printStackTrace();

            // new LogError("SocketGPRStask EmptyStackException");
            infoS.setIfsocketAttivo(false);

            infoS.setApriGPRS(false);
            infoS.setChiudiGPRS(false);
          } // catch

        } catch (Exception e) {
          close = true;
          // new LogError("SocketGPRSTask generic Exception");
          infoS.setIfsocketAttivo(false);

          infoS.setApriGPRS(false);
          infoS.setChiudiGPRS(false);
        }

        if (close) {

          try {
            semAT.getCoin(5);
            infoS.setATexec(true);
            mbox2.write("at^smong\r");
            while (infoS.getATexec()) {
              Thread.sleep(whileSleep);
            }
            semAT.putCoin();
          } catch (Exception e) {
          }

          try {
            // System.out.println("***************CLOSE******************");
            try {
              udpConn.close();
            } catch (NullPointerException e) {

            }
            // System.out.println("***************CLOSED******************");

            infoS.setTRKstate(false);
            infoS.setEnableCSD(true);

            semAT.getCoin(5);
            // Close GPRS channel
            // System.out.println("SocketGPRSTask: KILL GPRS");
            infoS.setATexec(true);
            mbox2.write("at+cgatt=0\r");
            while (infoS.getATexec()) {
              Thread.sleep(whileSleep);
            }

            semAT.putCoin();

            Thread.sleep(5000);
          } catch (InterruptedException e) {

          } catch (IOException e) {

          } catch (Exception e) {

          }
          System.out.println("WAIT - DISCONNECT GPRS");
          for (countDownException = 0; countDownException < 100; countDownException++) {
            if (infoS.isCloseUDPSocketTask()) break;
            try {
              Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
          }
          infoS.setApriGPRS(true);
        }
      } else {

        try {
          if (infoS.getInfoFileString(TrkState).equals("OFF")) {

            infoS.setTRKstate(false);
            infoS.setEnableCSD(true);
            semAT.putCoin(); // release AT interface
            try {
              semAT.getCoin(5);
              // Close GPRS channel
              // System.out.println("SocketGPRSTask: TRK OFF KILL GPRS");
              infoS.setATexec(true);
              mbox2.write("at+cgatt=0\r");
              while (infoS.getATexec()) {
                Thread.sleep(whileSleep);
              }
              semAT.putCoin();
            } catch (InterruptedException e) {
            }
          }
          Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
      }
    } // while
  } // run
Beispiel #4
0
  /**
   * Tries to send an event to it's recipient. If there is no connection to some
   * eu.funinnumbers.station event is saved in the event buffer.
   *
   * @param event the event to be sent
   */
  public synchronized void sendEvent(final Event event) { // NOPMD
    // Check if event should be sent to a Battle FGStationApp (checking type? id?)

    if (EchoProtocolManager.getInstance().getMyStation().isActive()) {
      try {
        // Creates a broadcast Datagram Connection
        dgConnection =
            (DatagramConnection)
                Connector.open(
                    "radiogram://"
                        + EchoProtocolManager.getInstance().getMyStation().getAddress().longValue()
                        + ":"
                        + DTSPORT);

        // Creates a Datagram using the above Connection
        final Datagram datagram = dgConnection.newDatagram(dgConnection.getMaximumLength());

        // Clean the Datagram
        datagram.reset();

        // Convert event to byte Array
        final byte[] eventArray = event.toByteArray();

        // Send Class Type
        datagram.writeUTF(event.getClass().getName());

        // Send length
        datagram.writeInt(eventArray.length);

        // Send array
        datagram.write(eventArray, 0, eventArray.length);

        // Send the datagram
        dgConnection.send(datagram);

        dgConnection.close();

        // There was a succefull update attempt after a failed one.
        if (failedUpdate) {
          Logger.getInstance().debug("Connection to eu.funinnumbers.station now seems to be OK");
          failedUpdate = false;

          // Try to empty events buffer again
          emptyEventBuffer();
        }
        Logger.getInstance().debug("Event sent succefully");

      } catch (Exception ex) {
        Logger.getInstance().debug("Unable to send event", ex);
        Logger.getInstance().debug("Adding event to storage: " + event.getDescription());
        // Close the open connection
        setDisconnected();

        // The attempt has failed
        failedUpdate = true;

        // Add event back to storage
        StorageService.getInstance().add(event);
        // FinnLogger.getInstance().increaseStoredEvents();

      }

    } else if (storageEnabled) {

      Logger.getInstance().debug("The connection seems to be inactive. Saving to buffer");
      // Add event to the corresponding recordstore
      StorageService.getInstance().add(event);
      // FinnLogger.getInstance().increaseStoredEvents();
    } else {
      Logger.getInstance().debug("Event lost!!!");
    }
  }
  /**
   * Send a message to a specified receiver address.
   *
   * @param msg message string to send.
   * @param receiverAddress Address of the place to send it to.
   * @param receiverPort the port to send it to.
   * @param receiverProtocol protocol to use to send.
   * @param retry try if connection was not successful at fi
   * @throws IOException If there is trouble sending this message.
   */
  protected void sendMessage(
      byte[] msg, String receiverAddress, int receiverPort, String receiverProtocol, boolean retry)
      throws IOException {
    if (LogWriter.needsLogging)
      LogWriter.logMessage(
          "Sending message to ["
              + receiverAddress
              + ":"
              + receiverPort
              + "/"
              + receiverProtocol
              + "]\n"
              + new String(msg)
              + "  to be sent to  ");

    // msg += "\r\n\r\n";
    // Via is not included in the request so silently drop the reply.
    if (receiverPort == -1) {
      if (LogWriter.needsLogging)
        LogWriter.logMessage(
            "DEBUG, UDPMessageChannel, sendMessage(),"
                + " The message is not sent: the receiverPort=-1");
      throw new IOException("Receiver port not set ");
    }
    if (Utils.compareToIgnoreCase(receiverProtocol, "UDP") == 0) {

      try {
        DatagramConnection socket;
        Datagram reply;
        boolean created = false;

        if (stack.udpFlag) {
          // Use the socket from the message processor (for firewall
          // support use the same socket as the message processor
          // socket -- feature request # 18 from java.net). This also
          // makes the whole thing run faster!
          socket = ((UDPMessageProcessor) messageProcessor).dc;

          // ArnauVP: this has the problem that the datagram created from this (inbound) connection
          // doesn't have an address assigned. Let's do it.
          reply = socket.newDatagram(msg, msg.length);
          reply.setAddress("datagram://" + peerAddress + ":" + peerPort);

        } else {
          // bind to any interface and port.
          // format: datagram://address:port
          socket = stack.getNetworkLayer().createDatagramSocket(peerAddress, peerPort);
          reply = socket.newDatagram(msg, msg.length);
          created = true;
        }
        if (LogWriter.needsLogging)
          LogWriter.logMessage(
              LogWriter.TRACE_DEBUG,
              "UDPMessageChannel, sendMessage(),"
                  + " Sending message over UDP, using socket "
                  + socket
                  + " created "
                  + created
                  + " destination "
                  + reply.getAddress());
        socket.send(reply);
        if (created) socket.close();
      } catch (IOException ex) {
        throw ex;
      } catch (Exception ex) {
        InternalErrorHandler.handleException(ex);
      }

    } else {
      // Use TCP to talk back to the sender.
      SocketConnection outputSocket =
          stack.ioHandler.sendBytes(peerAddress, peerPort, "tcp", msg, retry);
      OutputStream myOutputStream = stack.ioHandler.getSocketOutputStream(outputSocket);
      myOutputStream.write(msg, 0, msg.length);
      myOutputStream.flush();
      // The socket is cached (don't close it!);
    }
  }
  /**
   * Process an incoming datagram
   *
   * @param packet is the incoming datagram packet.
   */
  private void processIncomingDataPacket(Datagram packet) throws Exception {

    // For a request first via header tells where the message
    // is coming from.
    // For response, just get the port from the packet.
    // format: address:port
    String address = packet.getAddress();
    try {
      int firstColon = address.indexOf("//");
      int secondColon = address.indexOf(":", firstColon + 1);
      this.peerAddress = address.substring(firstColon + 2, secondColon);
      if (LogWriter.needsLogging)
        LogWriter.logMessage(
            LogWriter.TRACE_DEBUG, "UDPMessageChannel, run(), sender address:" + peerAddress);
      String senderPortString = address.substring(address.indexOf(";") + 1, address.indexOf("|"));
      this.peerPacketSourcePort = Integer.parseInt(senderPortString);
      if (LogWriter.needsLogging)
        LogWriter.logMessage(
            LogWriter.TRACE_DEBUG, "UDPMessageChannel, run(), sender port:" + peerPacketSourcePort);
    } catch (NumberFormatException e) {

      if (LogWriter.needsLogging)
        LogWriter.logMessage(
            LogWriter.TRACE_EXCEPTION,
            "UDPMessageChannel, run(), exception raised: " + e.getMessage());
      e.printStackTrace();
      peerPacketSourcePort = -1;
    }

    int packetLength = packet.getLength();
    // Read bytes and put it in a queue.
    byte[] msgBytes = packet.getData();

    // Do debug logging.
    if (LogWriter.needsLogging) {
      LogWriter.logMessage(
          LogWriter.TRACE_DEBUG,
          "UDPMessageChannel: processIncomingDataPacket : peerAddress = "
              + peerAddress
              + "/"
              + peerPacketSourcePort
              + " Length = "
              + packetLength
              + " msgBytes "
              + msgBytes);
    }

    Message sipMessage = null;
    try {
      receptionTime = System.currentTimeMillis();
      sipMessage = myParser.parseSIPMessage(msgBytes);
      myParser = null;
    } catch (ParseException ex) {
      myParser = null; // let go of the parser reference.
      if (LogWriter.needsLogging) {
        LogWriter.logMessage(LogWriter.TRACE_DEBUG, "Rejecting message !  " + new String(msgBytes));
        LogWriter.logMessage(LogWriter.TRACE_DEBUG, "error message " + ex.getMessage());
        LogWriter.logException(ex);
      }

      // TODO: do this on TCP too
      // JvB: send a 400 response for requests (except ACK)
      String msgString = new String(msgBytes, 0, packetLength);
      if (!msgString.startsWith("SIP/") && !msgString.startsWith("ACK ")) {

        String badReqRes = create400Response(msgString, ex);
        if (badReqRes != null) {
          if (LogWriter.needsLogging)
            LogWriter.logMessage(
                LogWriter.TRACE_DEBUG, "Sending automatic 400 Bad Request: " + badReqRes);
          try {
            this.sendMessage(badReqRes.getBytes(), peerAddress, peerPacketSourcePort, "UDP", false);
          } catch (IOException e) {
            LogWriter.logException(e);
          }
        } else {
          if (LogWriter.needsLogging)
            LogWriter.logMessage(
                LogWriter.TRACE_DEBUG, "Could not formulate automatic 400 Bad Request");
        }
      }

      return;
    }
    // No parse exception but null message - reject it and
    // march on (or return).
    // exit this message processor if the message did not parse.
    if (sipMessage == null) {
      if (LogWriter.needsLogging)
        LogWriter.logMessage(LogWriter.TRACE_DEBUG, "Rejecting message !  + Null message parsed.");
      return;
    }

    ViaList viaList = sipMessage.getViaHeaders();

    // Check for the required headers.
    if (sipMessage.getFromHeader() == null
        ||
        // sipMessage.getFromHeader().getTag() == null  ||
        sipMessage.getTo() == null
        || sipMessage.getCallId() == null
        || sipMessage.getCSeqHeader() == null
        || sipMessage.getViaHeaders() == null) {
      String badmsg = new String(msgBytes);
      if (LogWriter.needsLogging) {
        LogWriter.logMessage("bad message " + badmsg);
        LogWriter.logMessage(
            ">>> Dropped Bad Msg "
                + "FromHeader = "
                + sipMessage.getFromHeader()
                + "ToHeader = "
                + sipMessage.getTo()
                + "CallId = "
                + sipMessage.getCallId()
                + "CSeqHeader = "
                + sipMessage.getCSeqHeader()
                + "Via = "
                + sipMessage.getViaHeaders());
      }

      stack.logBadMessage(badmsg);
      return;
    }

    // For a request first via header tells where the message
    // is coming from.
    // For response, just get the port from the packet.
    if (sipMessage instanceof Request) {

      ViaHeader v = (ViaHeader) viaList.first();
      if (v.hasPort()) this.peerPort = v.getPort();
      else this.peerPort = SIPMessageStack.DEFAULT_PORT;

      this.peerProtocol = v.getTransport();

      boolean hasRPort = v.hasParameter(ViaHeader.RPORT);
      // Be warned, the host comparison may fail if socket.getAddress()
      // returns a domain name as the Via Host will be a numeric IP.
      // FIXME: No idea. Doing a DNS lookup or reverse DNS lookup
      // can be misleading because they can be non-matching, that is,
      // DNS(peerAddressName) != ReverseDNS(peerAddressIP)
      if (hasRPort || !this.peerAddress.equals(v.getHost())) {
        if (LogWriter.needsLogging)
          LogWriter.logMessage(
              LogWriter.TRACE_MESSAGES,
              "WARNING! \"Received\" parameter "
                  + "has been temporarily disabled. Response will be sent to topmost Via Host: "
                  + v.getHost());
        this.peerAddress = v.getHost();
        //                if (LogWriter.needsLogging)
        //	                   LogWriter.logMessage(LogWriter.TRACE_MESSAGES, "Adding \"received\"
        // parameter" +
        //	                   		" to incoming request with value: " + peerAddress +
        //	                   		" because it doesn't match the Via host " + v.getHost());
        //				v.setParameter(ViaHeader.RECEIVED, this.peerAddress);
      }

      if (hasRPort) {
        v.setParameter(ViaHeader.RPORT, Integer.toString(peerPacketSourcePort));
        this.peerPort = peerPacketSourcePort;
      }

    } else {
      this.peerPort = this.peerPacketSourcePort;
      this.peerProtocol = ((ViaHeader) viaList.getFirst()).getTransport();
    }

    processMessage(sipMessage);
  }