Ejemplo n.º 1
0
 @Override
 public boolean setIndications()
     throws TimeoutException, GatewayException, IOException, InterruptedException {
   int RETRIES = 3;
   int count = 0;
   while (count < RETRIES) {
     getModemDriver().write("AT+CNMI=?\r");
     try {
       this.cnmiDetector = new CNMIDetector(getModemDriver().getResponse());
       getModemDriver().write(this.cnmiDetector.getATCommand());
       getModemDriver().getResponse();
       return (getModemDriver().isOk());
     } catch (Exception e) {
       count++;
       Logger.getInstance()
           .logWarn(
               "Retrying the detection of CNMI, modem busy?", null, getGateway().getGatewayId());
       Thread.sleep(Service.getInstance().getSettings().AT_WAIT_CNMI);
     }
   }
   Logger.getInstance()
       .logWarn(
           "CNMI detection failed, proceeding with defaults.", null, getGateway().getGatewayId());
   return false;
 }
Ejemplo n.º 2
0
 @Override
 public void process() throws Exception {
   Logger.getInstance().logDebug("NotifyQueueManager running...", null, null);
   Notification notification = getNotifyQueue().take();
   if (notification instanceof GatewayStatusNotification) {
     if (Service.getInstance().getGatewayStatusNotification() != null) {
       GatewayStatusNotification n = (GatewayStatusNotification) notification;
       Service.getInstance()
           .getGatewayStatusNotification()
           .process(n.getGateway(), n.getOldStatus(), n.getNewStatus());
     }
   } else if (notification instanceof CallNotification) {
     if (Service.getInstance().getCallNotification() != null) {
       CallNotification n = (CallNotification) notification;
       Service.getInstance().getCallNotification().process(n.getGateway(), n.getCallerId());
     }
   } else if (notification instanceof InboundMessageNotification) {
     if (Service.getInstance().getInboundMessageNotification() != null) {
       InboundMessageNotification n = (InboundMessageNotification) notification;
       Service.getInstance()
           .getInboundMessageNotification()
           .process(n.getGateway(), n.getMsgType(), n.getMsg());
     }
   } else if (notification instanceof OutboundMessageNotification) {
     if (Service.getInstance().getOutboundMessageNotification() != null) {
       OutboundMessageNotification n = (OutboundMessageNotification) notification;
       Service.getInstance()
           .getOutboundMessageNotification()
           .process(n.getGateway(), n.getMsg());
     }
   }
   Logger.getInstance().logDebug("NotifyQueueManager end...", null, null);
 }
Ejemplo n.º 3
0
    public void onStateChange(SessionState newState, SessionState oldState, Object source) {
      if (newState.isBound()) {
        if (!getStatus().equals(GatewayStatuses.STARTED)) {
          try {
            JSMPPGateway.super.startGateway();
          } catch (TimeoutException e) {
            Logger.getInstance().logError("Failed starting Gateway.", e, getGatewayId());

          } catch (GatewayException e) {
            Logger.getInstance().logError("Failed starting Gateway.", e, getGatewayId());
          } catch (IOException e) {
            Logger.getInstance().logError("Failed starting Gateway.", e, getGatewayId());
          } catch (InterruptedException e) {
            Logger.getInstance().logError("Failed starting Gateway.", e, getGatewayId());
          }
        }
      } else if (newState.equals(SessionState.CLOSED)) {
        if (getStatus().equals(GatewayStatuses.STARTED)) {

          JSMPPGateway.super.setStatus(GatewayStatuses.RESTART);

          initSession();
        }
      }
      // System.out.println("State Changed: from "+oldState+" To "+newState);
    }
Ejemplo n.º 4
0
 @Override
 public void run() {
   try {
     if (isServiceRunning()) {
       Logger.getInstance().logDebug("InboundPollingTask() run.", null, null);
       readMessages();
     }
   } catch (Exception e) {
     Logger.getInstance().logDebug("Error in InboundPollingTask()", e, null);
   }
 }
Ejemplo n.º 5
0
 @Override
 protected void connectPort() throws GatewayException, IOException, InterruptedException {
   if (Service.getInstance().getSettings().SERIAL_NOFLUSH)
     Logger.getInstance()
         .logInfo("Comm port flushing is disabled.", null, getGateway().getGatewayId());
   if (Service.getInstance().getSettings().SERIAL_POLLING)
     Logger.getInstance()
         .logInfo("Using polled serial port mode.", null, getGateway().getGatewayId());
   try {
     Logger.getInstance()
         .logInfo(
             "Opening: " + getComPort() + " @" + getBaudRate(), null, getGateway().getGatewayId());
     CommPortIdentifier.getPortIdentifiers();
     setPortId(CommPortIdentifier.getPortIdentifier(getComPort()));
     setSerialPort(getPortId().open("org.smslib", 1971));
     setIn(getSerialPort().getInputStream());
     setOut(getSerialPort().getOutputStream());
     if (!Service.getInstance().getSettings().SERIAL_POLLING) {
       getSerialPort().notifyOnDataAvailable(true);
       getSerialPort().notifyOnOutputEmpty(true);
     }
     if (!Service.getInstance().getSettings().SERIAL_NOEVENTS) {
       getSerialPort().notifyOnBreakInterrupt(true);
       getSerialPort().notifyOnFramingError(true);
       getSerialPort().notifyOnOverrunError(true);
       getSerialPort().notifyOnParityError(true);
     } else
       Logger.getInstance().logInfo("Skipping registration of serial port events!", null, null);
     if (Service.getInstance().getSettings().SERIAL_RTSCTS_OUT)
       getSerialPort()
           .setFlowControlMode(
               SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
     else getSerialPort().setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
     getSerialPort().addEventListener(this);
     getSerialPort()
         .setSerialPortParams(
             getBaudRate(), SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
     getSerialPort().setInputBufferSize(Service.getInstance().getSettings().SERIAL_BUFFER_SIZE);
     getSerialPort().setOutputBufferSize(Service.getInstance().getSettings().SERIAL_BUFFER_SIZE);
     getSerialPort().enableReceiveThreshold(1);
     getSerialPort().enableReceiveTimeout(Service.getInstance().getSettings().SERIAL_TIMEOUT);
     if (Service.getInstance().getSettings().SERIAL_POLLING) {
       setPortReader(
           new PortReader(
               "PortReader() [" + getComPort() + "]",
               Service.getInstance().getSettings().SERIAL_POLLING_INTERVAL));
     }
   } catch (Exception e) {
     throw new GatewayException("Comm library exception: " + e.getMessage());
   }
 }
Ejemplo n.º 6
0
 @Override
 public boolean setIndications()
     throws TimeoutException, GatewayException, IOException, InterruptedException {
   try {
     // disable New Message Indications To Terminal Equipment
     getModemDriver().write("AT+CNMI=0,0,0,0,0\r");
     getModemDriver().getResponse();
   } catch (Exception e) {
     Logger.getInstance()
         .logWarn("Error disabling messageindication", null, getGateway().getGatewayId());
   }
   Logger.getInstance()
       .logInfo("ATHandler_Telit: CNMI detectiondisabled.", null, getGateway().getGatewayId());
   return false;
 }
Ejemplo n.º 7
0
  @Override
  public void startGateway()
      throws TimeoutException, GatewayException, IOException, InterruptedException {

    if (!session.getSessionState().isBound()) {
      if (enquireLink > 0) {
        session.setEnquireLinkTimer(enquireLink);
      }

      session.connectAndBind(
          host,
          port,
          new BindParameter(
              bindType,
              bindAttributes.getSystemId(),
              bindAttributes.getPassword(),
              bindAttributes.getSystemType(),
              bindTypeOfNumber,
              bindNumberingPlanIndicator,
              null));

    } else {
      Logger.getInstance().logWarn("SMPP session already bound.", null, getGatewayId());
      //	throw new GatewayException("Session already bound");
    }
  }
Ejemplo n.º 8
0
  private void init() {
    switch (bindAttributes.getBindType()) {
      case RECEIVER:
        bindType = BindType.BIND_RX;
        setInbound(true);
        setOutbound(false);
        break;
      case TRANSMITTER:
        bindType = BindType.BIND_TX;
        setInbound(false);
        setOutbound(true);
        break;
      case TRANSCEIVER:
        bindType = BindType.BIND_TRX;
        setInbound(true);
        setOutbound(true);
        break;
      default:
        IllegalArgumentException illegalArgumentException =
            new IllegalArgumentException("Unknown BindType " + bindAttributes.getBindType());
        Logger.getInstance()
            .logError(
                illegalArgumentException.getMessage(), illegalArgumentException, getGatewayId());
        throw illegalArgumentException;
    }

    bindTypeOfNumber =
        TypeOfNumber.valueOf(bindAttributes.getBindAddress().getTypeOfNumber().value());
    bindNumberingPlanIndicator =
        NumberingPlanIndicator.valueOf(
            bindAttributes.getBindAddress().getNumberingPlanIndicator().value());

    initSession();
  }
Ejemplo n.º 9
0
 public void serialEvent(SerialPortEvent event) {
   int eventType = event.getEventType();
   if (eventType == SerialPortEvent.OE)
     Logger.getInstance().logError("Overrun Error!", null, getGateway().getGatewayId());
   else if (eventType == SerialPortEvent.FE)
     Logger.getInstance().logError("Framing Error!", null, getGateway().getGatewayId());
   else if (eventType == SerialPortEvent.PE)
     Logger.getInstance().logError("Parity Error!", null, getGateway().getGatewayId());
   else if (eventType == SerialPortEvent.DATA_AVAILABLE) {
     if (!Service.getInstance().getSettings().SERIAL_POLLING) {
       synchronized (getSYNCReader()) {
         setDataReceived(true);
         getSYNCReader().notifyAll();
       }
     }
   }
 }
Ejemplo n.º 10
0
 @Override
 public void process(org.smslib.AGateway gateway, org.smslib.OutboundMessage msg) {
   Logger.getInstance()
       .logInfo(
           "Attempting or failed to send message from queue to: " + msg.getRecipient(),
           null,
           null);
 }
Ejemplo n.º 11
0
  // <editor-fold defaultstate="collapsed" desc="sendMessageToGroup">
  public String sendMessageToGroup(String groupName, List<String> recipients, String msg) {
    if (isServiceRunning()) {
      Service.getInstance().createGroup(groupName);
      for (String recepient : recipients) {
        Service.getInstance().addToGroup(groupName, recepient);
      }
      OutboundMessage message = new OutboundMessage(groupName, msg);

      try {
        Service.getInstance().sendMessage(message);
        Logger.getInstance().logInfo("Message Sent to Group: " + groupName, null, null);
        return "SUCCESS";
      } catch (TimeoutException ex) {
        Logger.getInstance().logError("Timeout error in sending message", ex, null);
        return "ERROR";
      } catch (GatewayException ex) {
        Logger.getInstance().logError("Gateway Exception in sending message", ex, null);
        return "ERROR";
      } catch (IOException ex) {
        Logger.getInstance().logError("IO Exception in sending message", ex, null);
        return "ERROR";
      } catch (InterruptedException ex) {
        Logger.getInstance().logError("Interrupted Exception in sending message", ex, null);
        return "ERROR";
      } finally {
        Service.getInstance().removeGroup(groupName);
      }
    } else {
      Logger.getInstance().logError("Service not running", null, null);
      return "SERVICE NOT RUNNING";
    }
  }
Ejemplo n.º 12
0
  @Override
  public void stopGateway()
      throws TimeoutException, GatewayException, IOException, InterruptedException {
    if (session.getSessionState().isBound()) {
      session.removeSessionStateListener(stateListener);
      session.unbindAndClose();

      // super.stopGateway();
    } else {
      Logger.getInstance().logWarn("SMPP session not bound.", null, getGatewayId());
      // throw new GatewayException("Session not bound");
    }
    super.stopGateway();
  }
Ejemplo n.º 13
0
 // <editor-fold defaultstate="collapsed" desc="stopSmsService()">
 public String stopSmsService() {
   if (Service.getInstance().getServiceStatus() == Service.ServiceStatus.STARTED) {
     try {
       Service.getInstance().stopService();
       inboundPollingTimer.cancel();
       return "SERVICE STOPPED";
     } catch (Exception ex) {
       Logger.getInstance().logError("Exception stopping service: ", ex, null);
       return "ERROR";
     }
   } else {
     return "SERVICE ALREADY STOPPED";
   }
 }
Ejemplo n.º 14
0
 @Override
 public void readStorageLocations() throws Exception {
   String response, loc;
   StringTokenizer tokens;
   getModemDriver().write("AT+CPMS=?\r");
   response = getModemDriver().getResponse();
   try {
     if (response.indexOf("+CPMS:") >= 0) {
       int i, j;
       i = response.indexOf('(');
       while (response.charAt(i) == '(') i++;
       j = i;
       while (response.charAt(j) != ')') j++;
       response = response.substring(i, j);
       tokens = new StringTokenizer(response, ",");
       while (tokens.hasMoreTokens()) {
         loc = tokens.nextToken().replaceAll("\"", "");
         if ((!loc.equalsIgnoreCase("MT")) && ((getStorageLocations().indexOf(loc) < 0)))
           addStorageLocation(loc);
       }
     } else {
       addStorageLocation("SM");
       Logger.getInstance()
           .logWarn(
               "CPMS detection failed, proceeding with default storage 'SM'.",
               null,
               getGateway().getGatewayId());
     }
   } catch (Exception e) {
     addStorageLocation("SM");
     Logger.getInstance()
         .logWarn(
             "CPMS detection failed, proceeding with default storage 'SM'.",
             null,
             getGateway().getGatewayId());
   }
 }
Ejemplo n.º 15
0
 @Override
 public boolean sendUSSDRequest(String presentation, String content, String dcs)
     throws GatewayException, TimeoutException, IOException, InterruptedException {
   String rawRequest = formatUSSDCommand(presentation, content, dcs);
   String ussdResponse = sendCustomATCommand(rawRequest);
   if (!ussdResponse.contains("OK")) {
     Logger.getInstance()
         .logError(
             "+CUSD command returned non-OK result: " + ussdResponse,
             null,
             getGateway().getGatewayId());
     return false;
   }
   return true;
 }
Ejemplo n.º 16
0
 @Override
 protected void disconnectPort() throws IOException, InterruptedException {
   synchronized (getSYNCReader()) {
     if (Service.getInstance().getSettings().SERIAL_POLLING) {
       if (getPortReader() != null) {
         getPortReader().cancel();
         setPortReader(null);
       }
     }
     if (getSerialPort() != null) getSerialPort().close();
     Logger.getInstance()
         .logInfo(
             "Closing: " + getComPort() + " @" + getBaudRate(), null, getGateway().getGatewayId());
   }
 }
Ejemplo n.º 17
0
 // <editor-fold defaultstate="collapsed" desc="sendOtaMessages">
 public String sendOtaMessage(String recipient, String url, String prompt) {
   String status = new String();
   try {
     OutboundWapSIMessage wapMsg = new OutboundWapSIMessage(recipient, new URL(url), prompt);
     wapMsg.setSignal(WapSISignals.HIGH);
     if (isServiceRunning()) {
       Service.getInstance().sendMessage(wapMsg);
       status = "WAP MESSAGE SENT";
     } else {
       status = "SERVICE IS NOT RUNNING";
     }
   } catch (Exception e) {
     status = "ERROR SENDING WAP MSG";
   }
   Logger.getInstance().logInfo(status, null, null);
   return status;
 }
Ejemplo n.º 18
0
 // <editor-fold defaultstate="collapsed" desc="startSmsService()">
 public String startSmsService() {
   if (Service.getInstance().getServiceStatus() == Service.ServiceStatus.STOPPED) {
     try {
       String result = loadConfiguration();
       if (!result.contains("ERROR")) {
         Service.getInstance().startService();
         int inbound_interval =
             Integer.parseInt(props.getProperty("settings.inbound_interval", "60"));
         inboundPollingTimer = new Timer("SmsService - InboundPollingTask");
         InboundPollingTask inboundPollingTask = new InboundPollingTask();
         inboundPollingTimer.schedule(
             inboundPollingTask, inbound_interval * 1000, inbound_interval * 1000);
       }
       return result;
     } catch (Exception ex) {
       Logger.getInstance().logError("Exception starting service: ", ex, null);
       return "ERROR = " + ex.getMessage();
     }
   } else {
     return "CANNOT START: SERVICE ALREADY STARTING/STARTED/STOPPING";
   }
 }
Ejemplo n.º 19
0
 @Override
 public String sendUSSDCommand(String ussdCommand, boolean interactive)
     throws GatewayException, TimeoutException, IOException, InterruptedException {
   String command = formatUSSDCommand(ussdCommand);
   // get the immediate result code
   String ussdResponse = sendCustomATCommand(command);
   if (!ussdResponse.contains("OK")) {
     Logger.getInstance()
         .logError(
             "+CUSD command returned non-OK result: " + ussdResponse,
             null,
             getGateway().getGatewayId());
     return null;
   }
   // get the unsolicted result
   ussdResponse = getModemDriver().getResponse(AsyncEvents.USSDRESPONSE);
   if (!interactive) {
     /*
      * This is a workaround for interactive USSD sessions which expect
      * further user input. We preemptively send an escape character which
      * will terminate such a session.
      */
     char esc = 0x1b;
     command = "" + esc + '\r';
     getModemDriver().write(command);
     getModemDriver().clearBuffer();
   }
   String response;
   String regex = "\"(.*)\"";
   Pattern pattern = Pattern.compile(regex);
   Matcher matcher = pattern.matcher(ussdResponse);
   if (matcher.find()) {
     response = formatUSSDResponse(matcher.group(1));
   } else {
     response = ussdResponse;
   }
   return response;
 }
Ejemplo n.º 20
0
 @Override
 public String readPhonebook(String loc) throws GatewayException, TimeoutException, IOException {
   String response;
   int minIndex, maxIndex;
   try {
     getModemDriver().write("AT+CPBS=\"" + loc + "\"\r");
     getModemDriver().getResponse();
     getModemDriver().write("AT+CPBR=?\r");
     response = getModemDriver().getResponse();
     response = response.replaceAll("\\s*\\+CPBR:\\s*", "");
     response = response.replaceAll("[()]", "");
     StringTokenizer tokens1 = new StringTokenizer(response, ",");
     StringTokenizer tokens2 = new StringTokenizer(tokens1.nextToken(), "-");
     minIndex = Integer.parseInt(tokens2.nextToken());
     maxIndex = Integer.parseInt(tokens2.nextToken());
     getModemDriver().write("AT+CPBR=" + minIndex + "," + maxIndex + "\r");
     response = getModemDriver().getResponse();
     return response;
   } catch (Exception e) {
     Logger.getInstance()
         .logWarn("Phonebook detection failed.", null, getGateway().getGatewayId());
     return "";
   }
 }
Ejemplo n.º 21
0
  // <editor-fold defaultstate="collapsed" desc=" Load Configuration from DHIS2 HOME ">
  private String loadConfiguration() throws Exception {
    String configFile = System.getenv("DHIS2_HOME") + File.separator + "SMSServer.conf";

    if (new File(configFile).exists()) {
      Collection<AGateway> existingGateways = new ArrayList<AGateway>();
      existingGateways.addAll(Service.getInstance().getGateways());

      // Remove all existing gateways
      for (AGateway gateway : existingGateways) {
        Service.getInstance().removeGateway(gateway);
      }

      // Load properties from configuration file
      FileInputStream f = new FileInputStream(configFile);
      this.props = new Properties();
      getProperties().load(f);
      f.close();

      // Add gateway to service based on configuration file
      // <editor-fold defaultstate="collapsed" desc=" Get Gateway & Configuration ">
      for (int i = 0; i < Integer.MAX_VALUE; i++) {
        try {
          String propName = "gateway." + i;
          String propValue = getProperties().getProperty(propName, "").trim();
          if (propValue.length() == 0) {
            break;
          }
          String modemName = propValue.split("\\,")[0].trim();
          if (modemName.contains("bulksms")) {
            String username = getProperties().getProperty("bulksms.username");
            String password = getProperties().getProperty("bulksms.password");
            BulkSmsHTTPGateway gateway =
                new BulkSmsHTTPGateway("bulksms.http.1", username, password);
            gateway.setOutbound(true);
            gateway.setInbound(true);
            Service.getInstance().addGateway(gateway);
          } else if (modemName.contains("clickatell")) {
            String username = getProperties().getProperty("clickatell.username");
            String password = getProperties().getProperty("clickatell.password");
            String api_id = getProperties().getProperty("clickatell.api_id");
            DhisClickatellGateway gateway =
                new DhisClickatellGateway("clickatell.http.1", api_id, username, password);
            gateway.setOutbound(true);
            gateway.setInbound(true);
            Service.getInstance().addGateway(gateway);
          } else {
            String port = getProperties().getProperty(modemName + ".port");
            int baudRate = Integer.parseInt(getProperties().getProperty(modemName + ".baudrate"));
            String manufacturer = getProperties().getProperty(modemName + ".manufacturer");
            String model = getProperties().getProperty(modemName + ".model");
            String protocol = getProperties().getProperty(modemName + ".protocol");
            String pin = getProperties().getProperty(modemName + ".pin");
            String inbound = getProperties().getProperty(modemName + ".inbound");
            String outbound = getProperties().getProperty(modemName + ".outbound");
            String simMemLocation = getProperties().getProperty(modemName + ".simMemLocation");

            // TODO: DETECT MODEM CLASS AND INSTANTIATE
            SerialModemGateway gateway =
                new SerialModemGateway(modemName, port, baudRate, manufacturer, model);

            if (simMemLocation != null && !simMemLocation.equals("-")) {
              gateway.getATHandler().setStorageLocations(simMemLocation);
            }

            if (protocol != null && protocol.equalsIgnoreCase("PDU")) {
              gateway.setProtocol(Protocols.PDU);
            } else {
              if (protocol != null && protocol.equalsIgnoreCase("TEXT")) {
                gateway.setProtocol(Protocols.TEXT);

              } else {
                gateway.setProtocol(Protocols.PDU);
              }
            }
            if (pin != null) {
              gateway.setSimPin(pin);
            }
            if (inbound.equalsIgnoreCase("yes")) {
              gateway.setInbound(true);
            } else {
              gateway.setInbound(false);
            }
            if (outbound.equalsIgnoreCase("yes")) {
              gateway.setOutbound(true);
            } else {
              gateway.setOutbound(false);
            }
            Service.getInstance().addGateway(gateway);
          }
          Logger.getInstance()
              .logInfo("Load Configuration: added gateway " + i + " / ", null, null);
        } catch (Exception e) {
          Logger.getInstance()
              .logError(
                  "Load Configuration: Unknown Gateway in configuration file!, " + e.getMessage(),
                  null,
                  null);
        }
      }
      // </editor-fold>
      return "SUCCESSFULLY STARTED SERVICE";
    } else {
      return "ERROR LOADING CONFIGURATION FILE";
    }
  }
Ejemplo n.º 22
0
  // <editor-fold defaultstate="collapsed" desc="readMessages()">
  void readMessages() {
    List<InboundMessage> msgList = new ArrayList<InboundMessage>();
    try {
      // Read the messages from SIM memory location, which are Inbound messages
      Service.getInstance().readMessages(msgList, InboundMessage.MessageClasses.ALL);
      Logger.getInstance()
          .logInfo(
              "Total messages read at " + Calendar.getInstance().getTime() + " = " + msgList.size(),
              null,
              null);
      if (msgList.size() > 0) {
        for (InboundMessage inMsg : msgList) {
          try {
            InboundBinaryMessage msg = (InboundBinaryMessage) inMsg;
            // Creating sms to store in database
            SmsInbound sms = new SmsInbound();

            // Set sms encoding
            if (msg.getEncoding() == MessageEncodings.ENC7BIT) {
              sms.setEncoding('7');
            } else {
              if (msg.getEncoding() == MessageEncodings.ENC8BIT) {
                sms.setEncoding('8');
              } else {
                if (msg.getEncoding() == MessageEncodings.ENCUCS2) {
                  sms.setEncoding('U');
                }
              }
            }

            sms.setGatewayId(msg.getGatewayId());
            sms.setMessageDate(new Date());
            sms.setOriginalReceiveDate(msg.getDate());
            sms.setOriginalRefNo(String.valueOf(msg.getMpRefNo()));
            sms.setOriginator(msg.getOriginator());
            sms.setProcess(0);
            sms.setReceiveDate(msg.getDate());
            sms.setText(new String(Compressor.decompress(msg.getDataBytes()), "UTF-8"));
            if (msg.getType() == MessageTypes.INBOUND) {
              sms.setType('I');
            } else {
              if (msg.getType() == MessageTypes.OUTBOUND) {
                sms.setType('O');
              } else {
                if (msg.getType() == MessageTypes.STATUSREPORT) {
                  sms.setType('S');
                } else {
                  sms.setType('U');
                }
              }
            }

            // saving sms into database
            smsInboundStoreService.saveSms(sms);
            Logger.getInstance().logDebug("Saved Sms from " + msg.getOriginator(), null, null);

            // Delete message based on configuration
            if (getProperties()
                .getProperty("settings.delete_after_processing", "no")
                .equalsIgnoreCase("yes")) {
              Service.getInstance().deleteMessage(msg);
            }
          } catch (ClassCastException ccex) {
            Logger.getInstance().logInfo("Ignoring incorrect formatted message", ccex, null);
          }
        }
      }
    } catch (Exception e) {
      Logger.getInstance().logError("SMSServer: reading messages exception!", e, null);
    }
  }
Ejemplo n.º 23
0
 @Override
 public int sendMessage(int size, String pdu, String phone, String text)
     throws TimeoutException, GatewayException, IOException, InterruptedException {
   int responseRetries, errorRetries;
   String response;
   int refNo = -1;
   if (getGateway().getProtocol() == Protocols.PDU) {
     errorRetries = 0;
     while (true) {
       responseRetries = 0;
       getModemDriver().write("AT+CMGS=\"_1_\"\r".replaceAll("\"_1_\"", "" + size));
       Thread.sleep(Service.getInstance().getSettings().AT_WAIT_CGMS);
       while (!getModemDriver().dataAvailable()) {
         responseRetries++;
         if (responseRetries == Service.getInstance().getSettings().OUTBOUND_RETRIES)
           throw new GatewayException("Gateway is not responding, max number of retries reached.");
         Logger.getInstance()
             .logWarn(
                 "ATHandler().SendMessage(): Still waiting for response (I) ("
                     + responseRetries
                     + ")...",
                 null,
                 getGateway().getGatewayId());
         Thread.sleep(Service.getInstance().getSettings().OUTBOUND_RETRY_WAIT);
       }
       responseRetries = 0;
       getModemDriver().clearBuffer();
       getModemDriver().write(pdu);
       getModemDriver().write((char) 26);
       response = getModemDriver().getResponse();
       while (response.length() == 0) {
         responseRetries++;
         if (responseRetries == Service.getInstance().getSettings().OUTBOUND_RETRIES)
           throw new GatewayException("Gateway is not responding, max number of retries reached.");
         Logger.getInstance()
             .logWarn(
                 "ATHandler().SendMessage(): Still waiting for response (II) ("
                     + responseRetries
                     + ")...",
                 null,
                 getGateway().getGatewayId());
         Thread.sleep(Service.getInstance().getSettings().OUTBOUND_RETRY_WAIT);
         response = getModemDriver().getResponse();
       }
       if (getModemDriver().getLastError() == 0) {
         Matcher m = Pattern.compile("\\s*\\+CMGS: *(\\d+)").matcher(response);
         if (m.find()) {
           refNo = Integer.parseInt(m.group(1));
         } else {
           // Message-Reference ID not returned
           refNo = -1;
         }
         break;
       } else if (getModemDriver().getLastError() > 0) {
         // CMS or CME error could happen here
         errorRetries++;
         if (errorRetries == Service.getInstance().getSettings().OUTBOUND_RETRIES) {
           Logger.getInstance()
               .logError(
                   getModemDriver().getLastErrorText() + ": Quit retrying, message lost...",
                   null,
                   getGateway().getGatewayId());
           refNo = -1;
           break;
         }
         Logger.getInstance()
             .logWarn(
                 getModemDriver().getLastErrorText() + ": Retrying...",
                 null,
                 getGateway().getGatewayId());
         Thread.sleep(Service.getInstance().getSettings().OUTBOUND_RETRY_WAIT);
       } else refNo = -1;
     }
   } else if (getGateway().getProtocol() == Protocols.TEXT) {
     getModemDriver().write("AT+CMGS=\"_1_\"\r".replaceAll("_1_", phone));
     getModemDriver().clearBuffer();
     getModemDriver().write(text);
     Thread.sleep(Service.getInstance().getSettings().AT_WAIT_CGMS);
     getModemDriver().write((char) 26);
     response = getModemDriver().getResponse();
     if (response.indexOf("OK\r") >= 0) {
       int i;
       StringBuilder tmp = new StringBuilder();
       i = response.indexOf(":");
       while (!Character.isDigit(response.charAt(i))) i++;
       while (Character.isDigit(response.charAt(i))) {
         tmp.append(response.charAt(i));
         i++;
       }
       refNo = Integer.parseInt(tmp.toString());
     } else refNo = -1;
   }
   return refNo;
 }
Ejemplo n.º 24
0
 @Override
 public void process(org.smslib.AGateway gateway, OutboundMessage msg) {
   Logger.getInstance()
       .logInfo("**** >>>> Now Sending: " + msg.getRecipient(), null, gateway.getGatewayId());
 }
Ejemplo n.º 25
0
 @Override
 public void process(org.smslib.AGateway gateway, String callerId) {
   Logger.getInstance().logInfo("Receiving call from: " + callerId, null, null);
 }
Ejemplo n.º 26
0
 @Override
 public void process(org.smslib.AGateway gateway, MessageTypes msgType, InboundMessage msg) {
   Logger.getInstance().logInfo("Received new message from: " + msg.getOriginator(), null, null);
 }
Ejemplo n.º 27
0
 public ATHandler_Telit(ModemGateway myGateway) {
   super(myGateway);
   Logger.getInstance().logInfo("ATHandler_Telit constructor.", null, getGateway().getGatewayId());
   Service.getInstance().getSettings().DISABLE_CMTI = true;
   Service.getInstance().getSettings().SERIAL_POLLING = true;
 }
Ejemplo n.º 28
0
    public void onAcceptDeliverSm(DeliverSm deliverSm) throws ProcessRequestException {
      if (MessageType.SMSC_DEL_RECEIPT.containedIn(deliverSm.getEsmClass())) {

        try {
          DeliveryReceipt delReceipt = deliverSm.getShortMessageAsDeliveryReceipt();

          StatusReportMessage statusReportMessage =
              new StatusReportMessage(
                  delReceipt.getId(),
                  deliverSm.getDestAddress(),
                  deliverSm.getSourceAddr(),
                  delReceipt.getText(),
                  delReceipt.getSubmitDate(),
                  delReceipt.getDoneDate());

          switch (delReceipt.getFinalStatus()) {
            case DELIVRD:
              statusReportMessage.setStatus(DeliveryStatuses.DELIVERED);
              break;
            case REJECTD:
            case EXPIRED:
            case UNDELIV:
              statusReportMessage.setStatus(DeliveryStatuses.ABORTED);
              break;
            default:
              statusReportMessage.setStatus(DeliveryStatuses.UNKNOWN);
          }

          statusReportMessage.setGatewayId(getGatewayId());
          Service.getInstance()
              .getNotifyQueueManager()
              .getNotifyQueue()
              .add(
                  new InboundMessageNotification(
                      getMyself(), MessageTypes.STATUSREPORT, statusReportMessage));
        } catch (InvalidDeliveryReceiptException e) {
          Logger.getInstance().logError("Failed getting delivery receipt.", e, getGatewayId());
        }
      } else {
        InboundMessage msg =
            new InboundMessage(
                new java.util.Date(),
                deliverSm.getSourceAddr(),
                new String(deliverSm.getShortMessage()),
                0,
                null);
        msg.setGatewayId(JSMPPGateway.this.getGatewayId());
        if (Alphabet.ALPHA_DEFAULT.value() == deliverSm.getDataCoding()) {
          msg.setEncoding(MessageEncodings.ENC7BIT);
        } else if (Alphabet.ALPHA_8_BIT.value() == deliverSm.getDataCoding()) {
          msg.setEncoding(MessageEncodings.ENC8BIT);
        } else if (Alphabet.ALPHA_UCS2.value() == deliverSm.getDataCoding()) {
          msg.setEncoding(MessageEncodings.ENCUCS2);
        } else {
          msg.setEncoding(MessageEncodings.ENCCUSTOM);
        }
        incInboundMessageCount();
        Service.getInstance()
            .getNotifyQueueManager()
            .getNotifyQueue()
            .add(new InboundMessageNotification(getMyself(), MessageTypes.INBOUND, msg));
      }
    }
Ejemplo n.º 29
0
  @Override
  public boolean sendMessage(OutboundMessage msg)
      throws TimeoutException, GatewayException, IOException, InterruptedException {

    Alphabet encoding = Alphabet.ALPHA_DEFAULT;

    switch (msg.getEncoding()) {
      case ENC8BIT:
        encoding = Alphabet.ALPHA_8_BIT;
        break;
      case ENCUCS2:
        encoding = Alphabet.ALPHA_UCS2;
        break;
      case ENCCUSTOM:
        encoding = Alphabet.ALPHA_RESERVED;
        break;
    }
    GeneralDataCoding dataCoding;

    switch (msg.getDCSMessageClass()) {
      case MSGCLASS_FLASH:
        dataCoding = new GeneralDataCoding(false, true, MessageClass.CLASS0, encoding);
        break;
      case MSGCLASS_ME:
        dataCoding = new GeneralDataCoding(false, true, MessageClass.CLASS1, encoding);
        break;
      case MSGCLASS_SIM:
        dataCoding = new GeneralDataCoding(false, true, MessageClass.CLASS2, encoding);
        break;
      case MSGCLASS_TE:
        dataCoding = new GeneralDataCoding(false, true, MessageClass.CLASS3, encoding);
        break;
      default:
        dataCoding = new GeneralDataCoding();
        dataCoding.setAlphabet(encoding);
    }
    try {
      final RegisteredDelivery registeredDelivery = new RegisteredDelivery();
      registeredDelivery.setSMSCDeliveryReceipt(
          (msg.getStatusReport())
              ? SMSCDeliveryReceipt.SUCCESS_FAILURE
              : SMSCDeliveryReceipt.DEFAULT);

      String msgId =
          session.submitShortMessage(
              bindAttributes.getSystemType(),
              TypeOfNumber.valueOf(sourceAddress.getTypeOfNumber().value()),
              NumberingPlanIndicator.valueOf(sourceAddress.getNumberingPlanIndicator().value()),
              (msg.getFrom() != null) ? msg.getFrom() : getFrom(),
              TypeOfNumber.valueOf(destinationAddress.getTypeOfNumber().value()),
              NumberingPlanIndicator.valueOf(
                  destinationAddress.getNumberingPlanIndicator().value()),
              msg.getRecipient(),
              new ESMClass(),
              (byte) 0,
              (byte) msg.getPriority(),
              null,
              formatTimeFromHours(msg.getValidityPeriod()),
              registeredDelivery,
              (byte) 0,
              dataCoding,
              (byte) 0,
              msg.getText().getBytes());
      msg.setRefNo(msgId);
      msg.setDispatchDate(new Date());
      msg.setGatewayId(getGatewayId());
      msg.setMessageStatus(MessageStatuses.SENT);
      incOutboundMessageCount();
    } catch (PDUException e) {
      msg.setGatewayId(getGatewayId());
      msg.setMessageStatus(MessageStatuses.FAILED);
      msg.setFailureCause(FailureCauses.BAD_FORMAT);
      Logger.getInstance().logError("Message Format not accepted.", e, getGatewayId());
      return false;
    } catch (ResponseTimeoutException e) {
      Logger.getInstance().logError("Message could not be sent.", e, getGatewayId());
      throw new TimeoutException(e.getMessage());
    } catch (InvalidResponseException e) {
      Logger.getInstance().logError("Message could not be sent.", e, getGatewayId());
      throw new IOException("InvalidResponseException: ", e);
    } catch (NegativeResponseException e) {
      Logger.getInstance().logError("Message could not be sent.", e, getGatewayId());
      throw new IOException("NegativeResponseException: ", e);
    }

    return true;
  }
Ejemplo n.º 30
0
 @Override
 public void stopGateway()
     throws TimeoutException, GatewayException, IOException, InterruptedException {
   Logger.getInstance().logInfo("Stopping gateway.", null, getGatewayId());
   super.stopGateway();
 }