@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"); } }
public static void main(String[] args) { SMPPSession session = new SMPPSession(); try { session.connectAndBind( "localhost", 8056, new BindParameter( BindType.BIND_TRX, "pavel", "wpsd", "cp", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null)); } catch (IOException e) { System.err.println("Failed connect and bind to host"); e.printStackTrace(); } // Set listener to receive deliver_sm session.setMessageReceiverListener(new MessageReceiverListenerImpl()); /* try { //String messageId = session.submitShortMessage("CMT", TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN, "1616", TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN, "628176504657", new ESMClass(), (byte) 0, (byte) 1, timeFormatter.format(new Date()), null, new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE), (byte) 0, DataCodings.ZERO, (byte) 0, "jSMPP simplify SMPP on Java platform".getBytes()); //System.out.println("Message submitted, message_id is " + messageId); } catch (PDUException e) { // Invalid PDU parameter System.err.println("Invalid PDU parameter"); e.printStackTrace(); } catch (ResponseTimeoutException e) { // Response timeout System.err.println("Response timeout"); e.printStackTrace(); } catch (InvalidResponseException e) { // Invalid response System.err.println("Receive invalid respose"); e.printStackTrace(); } catch (NegativeResponseException e) { // Receiving negative response (non-zero command_status) System.err.println("Receive negative response"); e.printStackTrace(); } catch (IOException e) { System.err.println("IO error occur"); e.printStackTrace(); } */ // session.unbindAndClose(); }
@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(); }
public void close() { connected = false; if (smppSession != null) { smppSession.close(); smppSession = null; } }
@Override public void setEnquireLink(int enquireLink) { super.setEnquireLink(enquireLink); if (session != null) { session.setEnquireLinkTimer(enquireLink); } }
private String sendMT( final String message, final TypeOfNumber sourceTon, final String source, final TypeOfNumber destinationTon, final String destination, OptionalParameter... optionalParameters) throws InvalidResponseException, PDUException, IOException, NegativeResponseException, ResponseTimeoutException { try { final String messageId = smppSession.submitShortMessage( serviceType, sourceTon, NumberingPlanIndicator.UNKNOWN, source, destinationTon, NumberingPlanIndicator.UNKNOWN, destination, new ESMClass(), (byte) 0, (byte) 1, null, null, new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE), (byte) 0, provider.getDataCoding(), (byte) 0, message.getBytes("ISO-8859-1"), optionalParameters); logger.info( "MT sent - messageId:{} to:{} from:{} text:{}{} - {}", messageId, destination, source, message, paramsToString(optionalParameters), this.toShortString()); return messageId; } catch (final PDUException e) { logger.error( "Failed to send MT - to:" + destination + " from:" + source + " text:" + message + paramsToString(optionalParameters) + " - " + this.toShortString(), e); throw e; } catch (final ResponseTimeoutException e) { logger.error( "Failed to send MT - to:" + destination + " from:" + source + " text:" + message + paramsToString(optionalParameters) + " - " + this.toShortString(), e); throw e; } catch (final InvalidResponseException e) { logger.error( "Failed to send MT - to:" + destination + " from:" + source + " text:" + message + paramsToString(optionalParameters) + " - " + this.toShortString(), e); throw e; } catch (final NegativeResponseException e) { logger.error( "Failed to send MT - to:" + destination + " from:" + source + " text:" + message + paramsToString(optionalParameters) + " - " + this.toShortString(), e); throw e; } catch (final IOException e) { logger.error( "Failed to send MT - to:" + destination + " from:" + source + " text:" + message + paramsToString(optionalParameters) + " - " + this.toShortString(), e); throw e; } catch (final Throwable e) { logger.error( "Failed to send MT - to:" + destination + " from:" + source + " text:" + message + paramsToString(optionalParameters) + " - " + this.toShortString(), e); throw new RuntimeException(e); } }
private void connect() throws IOException { if (connected) { return; } final SlooceSMPPSession smpp = this; smppSession = new SMPPSession( new SynchronizedPDUSender(new DefaultPDUSender(new DefaultComposer())), new DefaultPDUReader(), new SlooceSMPPSocketConnectionFactory(useSSL)); smppSession.setEnquireLinkTimer( provider .getEnquireLinkTimer()); // Depends on the provider's inactivity timeout (actually, this // is the SMPP Socket Read Timeout before enquiring to keep the // link alive) smppSession.setTransactionTimer( provider .getTransactionTimer()); // Depends on the provider's response timeout (responses should // be returned within a second) smppSession.setMessageReceiverListener( new MessageReceiverListener() { @Override public void onAcceptDeliverSm(final DeliverSm deliverSm) throws ProcessRequestException { try { doAcceptDeliverSm(deliverSm); } catch (Throwable t) { logger.error( "Failed to process incoming SMPP message " + deliverSm.toDebugString(), t); } } public void doAcceptDeliverSm(final DeliverSm deliverSm) throws ProcessRequestException { final Alphabet alphabet = smpp.provider.getAlphabet(deliverSm, logger); if (MessageType.SMSC_DEL_RECEIPT.containedIn(deliverSm.getEsmClass())) { // this message is a delivery receipt try { final DeliveryReceipt delReceipt = deliverSm.getShortMessageAsDeliveryReceipt(); String messageId = delReceipt.getId(); if (smpp.provider.isMessageIdDecimal()) { // Provider sends the messageId in a delivery receipt as a decimal value string // per the SMPP spec. // Convert it to hex to match the messageId hex string returned when submitting // the MT. messageId = Long.toHexString(Long.valueOf(messageId)); } final String operator = getOptionalParameterValueAsString( OptionalParameters.get( smpp.provider.getOperatorTag(), deliverSm.getOptionalParameters())); final SlooceSMPPMessage mt = new SlooceSMPPMessage( messageId, deliverSm.getSourceAddr(), operator, deliverSm.getDestAddress()); String message; if (alphabet == Alphabet.ALPHA_DEFAULT) { message = SlooceSMPPUtil.fromGSMCharset(delReceipt.getText().getBytes()); } else { message = delReceipt.getText(); } mt.setMessage(message); logger.info( "Received delivery receipt - mt:{} dataCoding:{} alphabet:{} esmClass:0x{} {}{} - {}", mt, deliverSm.getDataCoding(), alphabet, conventBytesToHexString(new byte[] {deliverSm.getEsmClass()}), sanitizeCharacters(delReceipt.toString()), paramsToString(deliverSm.getOptionalParameters()), smpp.toShortString()); if (smpp.receiver != null) { smpp.receiver.deliveryReceipt( mt, delReceipt.getFinalStatus(), delReceipt.getError(), smpp); } } catch (InvalidDeliveryReceiptException e) { logger.error("Failed getting delivery receipt - " + smpp.toShortString(), e); } } else { // this message is an incoming MO final String messageId = getOptionalParameterValueAsString( deliverSm.getOptionalParameter(OptionalParameter.Tag.RECEIPTED_MESSAGE_ID)); final String operator = getOptionalParameterValueAsString( OptionalParameters.get( smpp.provider.getOperatorTag(), deliverSm.getOptionalParameters())); byte[] messageBytes = deliverSm.getShortMessage(); byte[] udhBytes = new byte[0]; final SlooceSMPPMessage mo = new SlooceSMPPMessage( messageId, deliverSm.getSourceAddr(), operator, deliverSm.getDestAddress()); final boolean hasUDHI = GSMSpecificFeature.UDHI.containedIn(deliverSm.getEsmClass()); if (hasUDHI) { final int udhLength = messageBytes[0]; udhBytes = new byte[udhLength + 1]; System.arraycopy(messageBytes, 0, udhBytes, 0, udhLength + 1); byte[] messageBytesCopy = new byte[messageBytes.length - udhLength - 1]; System.arraycopy( messageBytes, udhLength + 1, messageBytesCopy, 0, messageBytes.length - udhLength - 1); messageBytes = messageBytesCopy; if (udhBytes[1] == 0x00) { // Concatenated short messages, 8-bit reference number mo.setCsmsReference(udhBytes[3] & 0xff); mo.setCsmsTotalParts(udhBytes[4] & 0xff); mo.setCsmsPartNumber(udhBytes[5] & 0xff); } else if (udhBytes[1] == 0x08) { // Concatenated short messages, 16-bit reference number mo.setCsmsReference(((udhBytes[3] & 0xff) << 8) | (udhBytes[4] & 0xff)); mo.setCsmsTotalParts(udhBytes[5] & 0xff); mo.setCsmsPartNumber(udhBytes[6] & 0xff); } else { // unsupported logger.warn("Unsupported udh:{}", conventBytesToHexString(udhBytes)); } } String message; if (alphabet == Alphabet.ALPHA_DEFAULT) { message = SlooceSMPPUtil.fromGSMCharset(messageBytes); } else if (alphabet == Alphabet.ALPHA_UCS2) { try { message = new String(messageBytes, "UTF-16"); } catch (UnsupportedEncodingException e) { logger.warn(e.getMessage()); message = new String(messageBytes); } } else { try { message = new String(messageBytes, "ISO-8859-1"); } catch (UnsupportedEncodingException e) { logger.warn(e.getMessage()); message = new String(messageBytes); } } if (smpp.stripSystemType && smpp.systemType != null) { message = Pattern.compile(smpp.systemType + "\\s*", Pattern.CASE_INSENSITIVE) .matcher(message) .replaceFirst(""); } mo.setMessage(message); logger.info( "Received message - mo:{} dataCoding:{} alphabet:{} esmClass:0x{} udh:0x{}{} - {}", mo, deliverSm.getDataCoding(), alphabet, conventBytesToHexString(new byte[] {deliverSm.getEsmClass()}), conventBytesToHexString(udhBytes), paramsToString(deliverSm.getOptionalParameters()), smpp.toShortString()); if (smpp.receiver != null) { smpp.receiver.mo(mo, smpp); } } } private String getOptionalParameterValueAsString( final OptionalParameter optionalParameter) { if (optionalParameter == null) { return null; } if (optionalParameter instanceof OptionalParameter.OctetString) { return ((OptionalParameter.OctetString) optionalParameter).getValueAsString(); } else { throw new RuntimeException( "OptionalParameter type is not yet supported: " + optionalParameter.getClass()); } } @Override public void onAcceptAlertNotification(final AlertNotification alertNotification) {} @Override public DataSmResult onAcceptDataSm(final DataSm dataSm, final Session source) throws ProcessRequestException { return null; } }); smppSession.addSessionStateListener( new SessionStateListener() { @Override public void onStateChange( final SessionState newState, final SessionState oldState, final Session source) { if (newState.equals(SessionState.CLOSED)) { if (smpp.connected) { logger.warn("Session closed - {}", smpp); smpp.connected = false; new Thread() { @Override public void run() { smpp.receiver.onClose(smpp); } }.start(); } else { logger.info("Session was already closed - {}", smpp); } } } }); smppSession.connectAndBind( host, port, new BindParameter( BindType.BIND_TRX, systemId, password, systemType, TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null)); connected = true; logger.info("Connected to {} using {}@{}:{} - {}", provider, systemId, host, port, smpp); }
public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("hello!"); String myLongMessage = "測試簡訊4_台新銀行理財商品處國際市場資訊: 美股連三漲," + "GE宣布將回購股票並退出風險較高的金融業務激勵大盤,道瓊漲0.6%、標普漲0.5%至2102點。" + "道瓊歐洲600漲0.9%續創新高。俄股跌0.4%、巴西股漲0.8%。美國油氣鑽井平台數連降18週," + "創1986年來最大降幅,布蘭特原油漲2.7%至58.1美元、西德州漲1.9%至51.8美元。南非幣貶0.5%至12。" + "隨上證昨漲1.9%至4034點,香港國企股近期動能亦增強,昨漲1.7%,港交所CEO李小加稱," + "未來滬港通投資額度會至少增20%~30%。惠譽(FITCH)對韓國及巴西債信展望一升一降," + "瑞銀分析師表示希臘近期違約機率已升高至50%以上。 美元兌離岸人民幣 (-0.0001=6.2178) " + "美元兌人民幣 (0.0028=6.2087) 歐元兌美元 (-0.0055=1.0604) 美元兌日圓 (-0.3600=120.22) " + "美元兌南非幣 (0.0554=11.9962) 美元兌新台幣 (0.0980=31.226) 美元對新幣 (-0.0018=1.3664) " + "澳幣兌美元 (-0.0010=0.7682) 黃金(美元/盎司) (1.1%=1207.6) 西德州中級原油(美元/桶) (2.3%=57.9) " + "布蘭特油價(美元/桶) (1.7%=51.6) 美國10年期公債殖利率 (-1.23bps=1.947%) :" + "本訊息僅供內部教育訓練使用,請勿外流"; System.out.println(myLongMessage.length()); SMPPSession smppSession = new SMPPSession(); byte[] msg = new byte[0]; try { OptionalParameter messagePayloadParameter = new OptionalParameter.OctetString( Tag.MESSAGE_PAYLOAD, new String(myLongMessage.getBytes("BIG5"), "iso8859-1")); smppSession.connectAndBind( "10.42.1.163", 2775, new BindParameter( BindType.BIND_TRX, "17life", "test17", "cln", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null)); /*System.out.println(smppSession.submitShortMessage("", TypeOfNumber.ALPHANUMERIC, NumberingPlanIndicator.UNKNOWN, "SmppTest", TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN, "886989235253", new ESMClass(), (byte)0, (byte)0, "", null, new RegisteredDelivery(SMSCDeliveryReceipt.DEFAULT), (byte)0, new GeneralDataCoding(false, true, MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT),(byte)0, msg, messagePayloadParameter));*/ String rspID = "14e70b619440a2a01a100c1fcd7ff97f"; String sndFrom = "85269171717"; org.jsmpp.bean.TypeOfNumber ton = TypeOfNumber.ALPHANUMERIC; try { Long.parseLong(sndFrom); ton = TypeOfNumber.INTERNATIONAL; } catch (NumberFormatException e) { // logger.error("not send from number:" + id.sndFrom + ":"); } QuerySmResult q4 = smppSession.queryShortMessage(rspID, ton, NumberingPlanIndicator.UNKNOWN, sndFrom); System.out.println(q4.getMessageState().value()); String str = "20" + q4.getFinalDate(); System.out.println(str.substring(0, str.length() - 4)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (PDUException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ResponseTimeoutException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidResponseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NegativeResponseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { smppSession.unbindAndClose(); } }
@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; }
private void initSession() { session = new SMPPSession(); session.addSessionStateListener(stateListener); session.setMessageReceiverListener(messageReceiver); }