Ejemplo n.º 1
0
 private OutboundMessage convertSMSToOutboundMsg(XProApplication application) {
   OutboundMessage outboundMsg = new OutboundMessage();
   outboundMsg.setPriority(2147483647);
   outboundMsg.setStatusReport(true);
   outboundMsg.setRecipient(application.getSmsReceiverNum());
   outboundMsg.setText(application.getSmsContent());
   return outboundMsg;
 }
Ejemplo n.º 2
0
 public OutboundMessage getOutboundMessage(String msg, String recipient) {
   OutboundMessage outboundMsg = new OutboundMessage();
   outboundMsg.setEncoding(MessageEncodings.ENCUCS2);
   outboundMsg.setDeliveryDelay(2000);
   try {
     outboundMsg.addText(msg);
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   outboundMsg.setRecipient(recipient);
   return outboundMsg;
 }
Ejemplo n.º 3
0
 /**
  * @param recipient
  * @param msg
  * @return
  * @throws Exception
  */
 public String sendMessage(String recipient, String msg) throws Exception {
   OutboundMessage outboundMessage = new OutboundMessage(recipient, msg);
   if (isServiceRunning()) {
     String longNumber = getProperties().getProperty("provider.longnumber").trim();
     if (longNumber != null && !longNumber.isEmpty()) {
       outboundMessage.setFrom(longNumber);
     }
     Service.getInstance().sendMessage(outboundMessage);
     return "MESSAGE SENT SUCCESSFULLY TO: " + recipient;
   } else {
     return "SERVICE IS NOT RUNNING";
   }
 }
Ejemplo n.º 4
0
  public void sendMsg() throws Exception {
    // this.srv.startService();
    Jedis redis = RedisUtil.getJedis();
    while (true) {
      List<String> bb = redis.blpop(0, "list");
      OutboundMessage msg;
      if (bb.get(1).equals("1")) {
        msg = new OutboundMessage("18514235966", "hello canyousdfdf¿ªÀÊreceadve");
      } else {
        msg = new OutboundMessage("18514235966", "322323 sdfdf¿ªÀÊreceadve");
      }

      msg.setEncoding(MessageEncodings.ENCUCS2);
      this.srv.sendMessage(msg);
      System.out.println(msg);
    }
  }
Ejemplo n.º 5
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.º 6
0
 /*
  * (non-Javadoc)
  *
  * @see org.smslib.smsserver.AInterface#getMessagesToSend()
  */
 @Override
 public Collection<OutboundMessage> getMessagesToSend() throws Exception {
   Collection<OutboundMessage> messageList = new ArrayList<OutboundMessage>();
   File[] outFiles =
       this.outDirectory.listFiles(
           new FileFilter() {
             public boolean accept(File f) {
               /* Read only unprocessed files with an .xml suffix */
               return (f.getAbsolutePath().endsWith(".xml")
                   && !getMessageCache().containsValue(f));
             }
           });
   for (int i = 0; i < outFiles.length; i++) {
     try {
       /* Process each document and add message to the list */
       OutboundMessage msg = readDocument(outFiles[i]);
       if (msg == null) {
         throw new IllegalArgumentException("Missing required fieldes!");
       }
       messageList.add(msg);
       getMessageCache().put(msg.getMessageId(), outFiles[i]);
     } catch (IllegalArgumentException e) {
       getService()
           .getLogger()
           .logWarn(
               "Skipping outgoing file "
                   + outFiles[i].getAbsolutePath()
                   + ": File is not valid: "
                   + e.getLocalizedMessage(),
               null,
               null);
       File brokenFile = new File(this.outBrokenDirectory, outFiles[i].getName());
       if (!outFiles[i].renameTo(brokenFile))
         getService()
             .getLogger()
             .logError("Can't move " + outFiles[i] + " to " + brokenFile, null, null);
     }
   }
   return messageList;
 }
Ejemplo n.º 7
0
 /*
  * (non-Javadoc)
  *
  * @see org.smslib.smsserver.AInterface#markMessage(org.smslib.OutboundMessage)
  */
 @Override
 public void markMessage(org.smslib.OutboundMessage msg) throws Exception {
   if (msg == null) {
     return;
   }
   File f = getMessageCache().get(msg.getMessageId());
   File newF = null;
   switch (msg.getMessageStatus()) {
     case SENT:
       newF = new File(this.outSentDirectory, f.getName());
       break;
     case FAILED:
       newF = new File(this.outFailedDirectory, f.getName());
       break;
     default:
       break;
   }
   if (f.renameTo(newF)) {
     getService().getLogger().logInfo(f + " marked.", null, null);
   } else {
     getService().getLogger().logWarn("Can't move " + f + " to " + newF, null, null);
   }
   getMessageCache().remove(msg.getMessageId());
 }
Ejemplo n.º 8
0
 /**
  * Reads a given node and tries to parse it
  *
  * @param n The node to parse
  * @return An outboundmessage if the node was parsable or null
  */
 private OutboundMessage readNode(Node n) {
   if ("message".equals(n.getNodeName())) {
     String recipient = null;
     String text = null;
     String originator = null;
     Element e = (Element) n;
     NodeList cnl = n.getChildNodes();
     /* Read required fields */
     for (int i = 0; i < cnl.getLength(); i++) {
       Node en = cnl.item(i);
       if ("recipient".equals(cnl.item(i).getNodeName())) {
         recipient = en.getTextContent();
       } else if ("text".equals(cnl.item(i).getNodeName())) {
         text = en.getTextContent();
       } else if ("originator".equals(cnl.item(i).getNodeName())) {
         originator = en.getTextContent();
       }
     }
     /* Create outbound message */
     OutboundMessage outMsg = new OutboundMessage(recipient, text);
     /* Set required fields */
     outMsg.setFrom(originator);
     if (!"".equals(e.getAttribute("create_date"))) {
       outMsg.setDate(getISO8601AsDate(e.getAttribute("create_date")));
     }
     if (!"".equals(e.getAttribute("gateway_id"))) {
       outMsg.setGatewayId(e.getAttribute("gateway_id"));
     }
     /* Read optional fields - priority */
     String priority = e.getAttribute("priority");
     if ("L".equalsIgnoreCase(priority)) {
       outMsg.setPriority(-1);
     } else if ("N".equalsIgnoreCase(priority)) {
       outMsg.setPriority(0);
     } else if ("H".equalsIgnoreCase(priority)) {
       outMsg.setPriority(+1);
     }
     /* Read optional fields - encoding */
     String encoding = e.getAttribute("encoding");
     if ("7".equals(encoding)) {
       outMsg.setEncoding(MessageEncodings.ENC7BIT);
     } else if ("8".equals(encoding)) {
       outMsg.setEncoding(MessageEncodings.ENC8BIT);
     } else {
       outMsg.setEncoding(MessageEncodings.ENCUCS2);
     }
     /* Read optinal fields - status_report */
     if ("1".equals(e.getAttribute("status_report"))) {
       outMsg.setStatusReport(true);
     }
     /* Read optinal fields - flash_sms */
     if ("1".equals(e.getAttribute("flash_sms"))) {
       outMsg.setFlashSms(true);
     }
     /* Read optinal fields - src_port */
     if (!"".equals(e.getAttribute("src_port"))) {
       outMsg.setSrcPort(Integer.parseInt(e.getAttribute("src_port")));
     }
     /* Read optinal fields - dst_port */
     if (!"".equals(e.getAttribute("dst_port"))) {
       outMsg.setDstPort(Integer.parseInt(e.getAttribute("dst_port")));
     }
     return outMsg;
   }
   return null;
 }
Ejemplo n.º 9
0
 @Override
 public void process(org.smslib.AGateway gateway, OutboundMessage msg) {
   Logger.getInstance()
       .logInfo("**** >>>> Now Sending: " + msg.getRecipient(), null, gateway.getGatewayId());
 }
Ejemplo n.º 10
0
 @Override
 public boolean sendMessage(OutboundMessage msg)
     throws TimeoutException, GatewayException, IOException, InterruptedException {
   URL url = null;
   List<HttpHeader> request = new ArrayList<HttpHeader>();
   List<String> response;
   String reqLine;
   boolean ok = false;
   request.add(new HttpHeader("username", this.username, false));
   request.add(new HttpHeader("password", this.password, false));
   request.add(new HttpHeader("message", msg.getText(), false));
   request.add(new HttpHeader("msisdn", msg.getRecipient().substring(1), false));
   request.add(new HttpHeader("allow_concat_text_sms", "1", false));
   if (msg.getStatusReport()) request.add(new HttpHeader("want_report", "1", false));
   if (msg.getFlashSms()) request.add(new HttpHeader("msg_class", "0", false));
   if (msg.getFrom() != null && msg.getFrom().length() != 0)
     request.add(new HttpHeader("source_id", msg.getFrom(), false));
   else if (getFrom() != null && getFrom().length() != 0)
     request.add(new HttpHeader("source_id", getFrom(), false));
   reqLine = ExpandHttpHeaders(request);
   url = new URL(this.providerUrl + "/eapi/submission/send_sms/2/2.0" + "?" + reqLine);
   synchronized (this.SYNC_Commander) {
     response = HttpGet(url);
   }
   if (response.get(0).charAt(0) == '0') {
     StringTokenizer tokens = new StringTokenizer(response.get(0), "|");
     tokens.nextToken();
     tokens.nextToken();
     msg.setRefNo(tokens.nextToken());
     msg.setDispatchDate(new Date());
     msg.setGatewayId(getGatewayId());
     msg.setMessageStatus(MessageStatuses.SENT);
     incOutboundMessageCount();
     ok = true;
   } else {
     StringTokenizer tokens = new StringTokenizer(response.get(0), "|");
     switch (Integer.parseInt(tokens.nextToken())) {
       case 22:
         msg.setFailureCause(FailureCauses.GATEWAY_FAILURE);
         break;
       case 23:
         msg.setFailureCause(FailureCauses.GATEWAY_AUTH);
         break;
       case 24:
         msg.setFailureCause(FailureCauses.BAD_FORMAT);
         break;
       case 25:
       case 26:
       case 27:
       case 28:
         msg.setFailureCause(FailureCauses.NO_CREDIT);
         break;
       case 40:
         msg.setFailureCause(FailureCauses.GATEWAY_FAILURE);
         break;
     }
     msg.setRefNo(null);
     msg.setDispatchDate(null);
     msg.setMessageStatus(MessageStatuses.FAILED);
     ok = false;
   }
   return ok;
 }
  /**
   * @param smsMessage
   * @param msg
   * @return
   * @throws PersistenceException
   */
  @Override
  public SendModem2Info saveOrUpdate(SendSMSMessage smsMessage, OutboundMessage msg)
      throws PersistenceException {
    SendModem2Info config = new SendModem2Info();

    config.setGatewayID(msg.getGatewayId());

    config.setMessageId(String.valueOf(msg.getMessageId()));
    config.setMessageUUID(msg.getUuid());
    config.setEncoding(msg.getEncoding().toString());
    config.setDataGerada(msg.getDate().toString());
    config.setSmscRefNum(msg.getRefNo());
    config.setNumDestinatario(smsMessage.getNumero());
    if (msg.getDispatchDate() == null) {

      config.setDataExapedicao("Não há data prevista para expedição");

    } else {
      config.setDataExapedicao(msg.getDispatchDate().toString());
    }
    config.setMsgStatus(msg.getMessageStatus().toString());
    config.setCausaFalha(String.valueOf(msg.getFailureCause()));
    config.setPeriodoValido(String.valueOf(msg.getValidityPeriod()));
    config.setRelatorioStatus(msg.getStatusReport());
    config.setPortaDestino(String.valueOf(msg.getSrcPort()));
    config.setFlashSMS(msg.getFlashSms());
    config.setMensagem(smsMessage.getMensagem());
    config.setPduData(msg.getPduUserData());

    if (msg.getScheduledDeliveryDate() == null) {

      config.setEntregaPrevista("SEM DATA PREVISTA");
    } else {
      config.setEntregaPrevista(msg.getScheduledDeliveryDate().toString());
    }
    return new BaseRepository<SendModem2Info>(SendModem2Info.class).saveOrUpdate(config);
  }
Ejemplo n.º 12
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.º 13
0
  private void TransmitirSMS() {

    try {
      List<MdlAlertameEnviados> SMSEnviarList =
          Persistence.Listar("from MdlAlertameEnviados e where e.transmitido = " + 0 + "");

      if (!SMSEnviarList.isEmpty()) {
        for (MdlAlertameEnviados sms : SMSEnviarList) {
          try {
            Long userid = sms.getUserid();
            String mensagem = sms.getMensagem();
            MdlUser User = (MdlUser) Persistence.carregar(userid, MdlUser.class);
            String number = "";

            String phone1 = User.getPhone1();

            if (!phone1.equals("")) {
              if (phone1.contains("(")) {
                number =
                    User.getPhone1()
                        .replaceAll(Pattern.quote("("), "")
                        .replaceAll(Pattern.quote(")"), "")
                        .replaceAll(Pattern.quote("-"), "")
                        .replaceAll(Pattern.quote(" "), "");
              } else {
                number = phone1;
              }
            } else {
              String phone2 = User.getPhone2();
              if (!phone2.equals("")) {
                if (phone2.contains("(")) {
                  number =
                      User.getPhone2()
                          .replaceAll(Pattern.quote("("), "")
                          .replaceAll(Pattern.quote(")"), "")
                          .replaceAll(Pattern.quote("-"), "")
                          .replaceAll(Pattern.quote(" "), "");
                } else {
                  number = phone2;
                }
              } else {
                MailUtil.sendEmailError(
                    "Usuario: " + User.toString() + " Sem numero de telefone cadastrado!");
              }
            }

            if (!number.equals("")) {

              System.out.println("###########################   Number: " + number);

              OutboundMessage msg = SMSUtil.getInstance().sendMessage(number, mensagem);

              String status = msg.getMessageStatus().name();

              if (status.equalsIgnoreCase("SENT")) {
                long currentTimeMillis = System.currentTimeMillis();
                sms.setTransmitido(new Long(1));
                sms.setHorario(currentTimeMillis);

                Persistence.atualizar(sms);

              } else if (status.equalsIgnoreCase("FAILED")) {

                // executar um comportamento que verifica a causa do erro
                // estudar todos os erros possiveis gerados pelo SMSLib
                // pra tentar se auto corrigir
                // MailUtil.sendEmailError(msg.toString());
              }
            }
          } catch (Exception ex) {
            MailUtil.sendEmailError(ex);
            Logger.getLogger(ReEnviarSMS.class.getName()).log(Level.SEVERE, null, ex);
          }
        }
      } else {
        System.out.println("Nada a ser enviado!");
        block();
      }
    } catch (Exception ex) {
      MailUtil.sendEmailError(ex);
      Logger.getLogger(ReEnviarSMS.class.getName()).log(Level.SEVERE, null, ex);
    }
  }