/**
   * Means to process PDUs received from the SMSC. This method is called by the <code>Receiver
   * </code> whenever a PDU is received from the SMSC.
   *
   * @param request the request received from the SMSC.
   */
  public void handleEvent(ServerPDUEvent event) {
    PDU pdu = event.getPDU();
    // System.out.println("pdu.ServerPDUEvent()" + pdu.debugString());
    if (pdu.isValid()) {
      if (pdu.isRequest()) {
        // Logger.println("==> " + pdu.debugString());

        // Make default response
        Response response = ((Request) pdu).getResponse();
        this.toSMSC.enqueue(response);
        if (pdu.getCommandId() != Data.ENQUIRE_LINK) {
          this.processRequest(pdu);
        }

      } else if (pdu.isResponse()) {
        // System.out.println("pdu.getCommandId()" +
        // pdu.getCommandId());
        // System.out.println("Data.ENQUIRE_LINK_RESP" +
        // Data.ENQUIRE_LINK_RESP);
        if (pdu.getCommandId() != Data.ENQUIRE_LINK_RESP) this.responseQueue.enqueue(pdu);
        // Gateway.util.log(this.getClass().getName(),"{Respond for
        // MT}{MessageId=" + pdu.getSequenceNumber() +"}");
      } else {
        // System.out
        //		.println("pdu of unknown class (not request nor response) "
        //				+ "received; Discarding " + pdu.debugString());

        DBTools.ALERT(
            "PDUEventListener",
            "PDUEventListener",
            Constants.ALERT_WARN,
            "pdu of unknown class (not request nor response) "
                + "received; Discarding "
                + pdu.debugString(),
            Preference.ALERT_CONTACT);
      }
    } else {
      // System.out.println("Received an invalid pdu!");

      DBTools.ALERT(
          "PDUEventListener",
          "PDUEventListener",
          Constants.ALERT_WARN,
          "Received an invalid pdu!",
          Preference.ALERT_CONTACT);
    }
  }
  public void run() {
    // ///////////////////////////
    Gateway.addLiveThread(this);
    // ///////////////////////////
    while (Gateway.running) {
      try {
        pdud = (PDUData) fromSMSC.dequeue(); // blocks until having
        // an item
        // pdu = (PDU) fromSMSC.dequeue(); //blocks until having an item
        pdu = (PDU) pdud.getPDU();
        if (pdu.isRequest()) {
          this.RequestID = pdud.getRequestID();
          processRequest(pdu);
        }
      } catch (DBException ex) { // when lost connection to db
        Logger.error(this.getClass().getName(), "DBException: " + ex.getMessage());
        DBTools.ALERT(
            "RequestProcessor",
            "RequestProcessor",
            Constants.ALERT_WARN,
            Preference.Channel + "DBException: " + ex.getMessage(),
            Preference.ALERT_CONTACT);
        Logger.error(this.getClass().getName(), "Alert2YM DBException: " + ex.getMessage());
      } catch (Exception e) {
        Logger.error(this.getClass().getName(), "Exception: " + e.getMessage());

        DBTools.ALERT(
            "RequestProcessor",
            "RequestProcessor",
            Constants.ALERT_WARN,
            Preference.Channel + "Exception: " + e.getMessage(),
            Preference.ALERT_CONTACT);
      }

      try {
        Thread.sleep(50);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    // /////////////////////////////
    Logger.info(this.getClass().getName(), "{" + this.getClass().getName() + " stopped}");
    this.destroy();
    // /////////////////////////////
  }
  private void processRequest(PDU pdu) throws DBException, IOException {
    // Process the request and add to SMS_RECEIVE_QUEUE
    if (pdu.getCommandId() == Data.DELIVER_SM) {

      dsm = (DeliverSM) pdu;
      this.userId = dsm.getSourceAddr().getAddress();
      this.serviceId = dsm.getDestAddr().getAddress();
      this.info = dsm.getShortMessage();

      ByteBuffer da = null;

      try {
        da = dsm.getDestSubaddress();

        String te = Convert.hexToString(da.getHexDump().substring(2));

        //				this.RequestID = te;
        Gateway.util.log(this.getClass().getName(), "getDestSubaddress:" + te);
      } catch (ValueNotSetException ex) {

      }
      short destport = 0;
      try {
        destport = dsm.getDestinationPort();

        Gateway.util.log(this.getClass().getName(), "getDestinationPort:" + destport);
      } catch (ValueNotSetException e) {
        // TODO Auto-generated catch block
        // Tim Dport o day
        // ByteBuffer otaData =new
        // ByteBuffer(info.getBytes(Data.ENC_ISO8859_1));
        ByteBuffer otaData = new ByteBuffer();
        otaData = dsm.getShortMessagebuff();
        try {

          byte udhlength = otaData.removeByte();
          byte udhele1 = otaData.removeByte();
          byte udhele2 = otaData.removeByte();

          short sdport = otaData.removeShort();

          short ssport = otaData.removeShort();

          String newmsg = otaData.removeString(otaData.length(), Data.ENC_ISO8859_1);

          if (udhlength == 6 && udhele1 == 5) {
            destport = sdport;
            this.info = newmsg;
            Gateway.util.log(
                this.getClass().getName(), "getDestinationPort:" + destport + "@info=" + newmsg);
          }

        } catch (NotEnoughDataInByteBufferException e1) {
          // TODO Auto-generated catch block

        }
      }

      this.Dport = Short.toString(destport);

      if (this.info == null) {
        this.info = "null";
      }
      this.userId = removePlusSign(this.userId);
      this.serviceId = rebuildServiceId(this.serviceId);
      this.operator = Preference.mobileOperator;
      // Added on 22//2003 : VinaPhone gui ban tin DeliverReport voi
      // truong esm_class != 0x4. ==> He thong xem nhu ban tin thuong
      // sai format va gui thong bao -- report -- thong bao --> LOOP./
      // To pass over this, set:

      if (dsm.getEsmClass() == 0x4 || info.startsWith("id:")) { // DeliverReport
        // (not
        // processed)!
        Gateway.util.log(this.getClass().getName(), "It can be DeliverReport (not processed)!");
        return; // not processed
      }

      // Normal message (request):
      // Neu mobile o che do tieng viet
      // --> Loai bo space (ky tu 00) giua cac ky tu
      this.info = StringTool.removeChar(this.info, '\00');

      String newserviceid = this.serviceId;

      newserviceid = newserviceid.substring(newserviceid.length() - 4);

      // DANND add
      DateFormat dateFormat = new SimpleDateFormat("MMddHHmmssSSS");
      java.util.Date date = new java.util.Date();
      String datetime = dateFormat.format(date);
      this.RequestID = Preference.prefix_requestid + datetime + threadId;

      dbTools.add2SMSReceiveQueueR(
          this.userId,
          this.serviceId,
          this.operator,
          this.commandCode,
          this.info,
          this.RequestID,
          this.Dport);
    }
  }
  // ===================================================================
  private void processRequest(PDU pdu) {
    try {
      switch (pdu.getCommandId()) {
        case Data.DELIVER_SM:
          dsm = (DeliverSM) pdu;
          if (dsm.getEsmClass() == 0x04) {
            // this.deliveryQueue.enqueue(pdu);
            Logger.info(this.getClass().getName(), "dsm.getEsmClass() == 0x04");
          } else {
            DateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmssSSS");
            java.util.Date date = new java.util.Date();
            String datetime = dateFormat.format(date);

            PDUData pd = new PDUData();
            pd.setPDU(pdu);
            pd.setRequestID(Preference.prefix_requestid + datetime);

            this.requestQueue.enqueue(pd);
            // dsm.setSourceAddr(new Address("095"));
            String userid = dsm.getSourceAddr().getAddress();

            dsm.setSourceAddr(
                Preference.formatUserIdMO(userid, Constants.USERID_FORMAT_INTERNATIONAL));

            String dsmLog =
                "{MO-comes}{Request_ID="
                    + Preference.prefix_requestid
                    + datetime
                    + "}{UserID="
                    + dsm.getSourceAddr().getAddress()
                    + "}{ServiceID="
                    + dsm.getDestAddr().getAddress()
                    + "}{Info="
                    + dsm.getShortMessage()
                    + "}";
            Logger.info(this.getClass().getName(), dsmLog);
          }
          break;
        case Data.DATA_SM:
          // System.out.println(" Data_SM --> Not processed.");
          Logger.error(this.getClass().getName(), "  Data_SM --> Not processed.");
          break;
        case Data.UNBIND:
          Logger.info(this.getClass().getName(), "  Data.UNBIND --> Not processed.");
          this.requestQueue.enqueue(pdu);
          break;
        default:
          Logger.error("processRequest: Unspecified SM " + pdu.debugString());
      }
    } catch (Exception e) {

      Logger.error(this.getClass().getName(), "Exception " + e.toString());

      DBTools.ALERT(
          "PDUEventListener",
          "processRequest",
          Constants.ALERT_WARN,
          Preference.Channel + "@processRequest:" + e.toString(),
          Preference.ALERT_CONTACT);
      Logger.printStackTrace(e);
    }
  }