pax_global_header00006660000000000000000000000064124611310510014504gustar00rootroot0000000000000052 comment=468daccea90c577d04d6383791f96ab088e7a130 jsmpp-2.1.2/000077500000000000000000000000001246113105100126375ustar00rootroot00000000000000jsmpp-2.1.2/.travis.yml000066400000000000000000000000601246113105100147440ustar00rootroot00000000000000language: java jdk: - oraclejdk7 - openjdk6 jsmpp-2.1.2/CHANGES.txt000066400000000000000000000027151246113105100144550ustar00rootroot00000000000000Changes: 2.0 beta 3 - Add SMPP Server component - Add Optional Parameter support (contribution from mikko.koponen@gmail.com) - Handling PDU processing concurrently (performance improvement) - Add data_sm support - Add cancel_sm support - Add replace_sm support - Add alert_notification support - Add CapacityPolicy to PDUByteBuffer (performance improvement, minimize array of byte creation) 2.0 beta 4 - Modify Optional Parameter API (currently for TLV related to message concatenation case) - Add ServerResponseDeliveryListener (listener to receive success or failure event of submit_sm_resp/submit_multi_resp delivery) - Change license from LGPL to "Apache License, Version 2.0" - Add license notice on every sources. 2.0 beta 5 - Bug fix for type on OptionalParameters class - Update the SessionState way to return the value from: 1. isBound() 2. isTransmittable() 3. isReceiveable() - Add examples for auto-reconnect gateway it can be found on org.jsmpp.examples.gateway - Fix the destination addresses on SMPPSession#submitMultiple Some classes and interfaces created to support the bug fixes. - Fix the date parsing on delivery receipt - Referring to Appendix C of SMPP 3.4 for year parsing rule 2.0 beta 6 - Change the max length of short message to 254, referring to SMPP 3.4 Previously using 255 (taken from SMPP 5.0) 2.1.0 - set connection timeout when binding - provide source (the session) for onAcceptDataSm - use StrictBufferedInputStreamjsmpp-2.1.2/LICENSE.txt000066400000000000000000000236751246113105100144770ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS jsmpp-2.1.2/README.md000066400000000000000000000027151246113105100141230ustar00rootroot00000000000000 Introduction ------------ jSMPP is a java implementation (SMPP API) of SMPP protocol (currently support SMPP v3.4). It provides interfaces to communicate with Message Center or ESME (External Short Message Entity) and able to handle traffic 3000-5000 messages per second. jSMPP is not a high-level library. Many people looking for a quick way to get started with SMPP may be better of using an abstraction layer such as the Apache Camel SMPP component: http://camel.apache.org/smpp.html Travis-CI status: ----------------- [![Build Status](https://travis-ci.org/opentelecoms-org/jsmpp.svg?branch=release-2.1)](https://travis-ci.org/opentelecoms-org/jsmpp) History ------- The project started on Google Code: http://code.google.com/p/jsmpp/ It was maintained by uudashr on Github until 2013 It is now a community project maintained at http://jsmpp.org Release procedure ----------------- mvn deploy -DperformRelease=true -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ -DrepositoryId=sonatype-nexus-staging * log in here: https://oss.sonatype.org * click the `Staging Repositories' link * select the repository and click close * select the repository and click release License ------- Copyright (C) 2007-2013, Nuruddin Ashr Copyright (C) 2012-2013, Denis Kostousov Copyright (C) 2014, Daniel Pocock http://danielpocock.com This project is licensed under the Apache Software License 2.0. jsmpp-2.1.2/build.xml000066400000000000000000000132461246113105100144660ustar00rootroot00000000000000 jsmpp-2.1.2/comment_template.txt000066400000000000000000000010701246113105100167330ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */jsmpp-2.1.2/pom.xml000066400000000000000000000251121246113105100141550ustar00rootroot00000000000000 4.0.0 org.jsmpp jsmpp 2.1.2 bundle jSMPP SMPP library for Java http://jsmpp.org Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo Denis Kostousov Nuruddin Ashr Daniel Pocock daniel@pocock.pro http://danielpocock.com yyyyMMddHHmm ${maven.build.timestamp} UTF-8 1.6.1 1.2.17 git.properties junit junit 4.8.2 test org.slf4j slf4j-api ${slf4j.version} org.testng testng 5.14.10 test org.slf4j slf4j-log4j12 ${slf4j.version} org.slf4j slf4j-simple ${slf4j.version} commons-codec commons-codec 1.4 log4j log4j ${log4j.version} org.sonatype.oss oss-parent 7 org.apache.maven.wagon wagon-ssh 2.0 org.apache.maven.wagon wagon-ssh-external 2.0 org.apache.maven.plugins maven-compiler-plugin 2.3.2 1.6 1.6 utf-8 org.apache.maven.plugins maven-release-plugin org.apache.felix maven-bundle-plugin 2.3.5 true ${project.artifactId} ${project.groupId}.${project.artifactId} org.jsmpp org.slf4j;resolution:=optional, * jsmpp ${project.version} biz.aQute.bnd bndlib 2.4.0 org.apache.maven.plugins maven-release-plugin 2.1 maven-source-plugin 2.1.2 verify jar-no-fork pl.project13.maven git-commit-id-plugin 1.9 initialize revision git dd.MM.yyyy '@' HH:mm:ss z true true ${git.properties} org.codehaus.mojo properties-maven-plugin 1.0-alpha-2 initialize read-project-properties ${git.properties} maven-jar-plugin 2.3.2 true true ${project.version}-${git.branch}.${git.commit.id.abbrev} org.apache.log4j release-sign-artifacts performRelease true org.apache.maven.plugins maven-gpg-plugin 1.4 sign-artifacts verify sign https://github.com/opentelecoms-org/jsmpp scm:git:ssh://git@github.com:opentelecoms-org/jsmpp.git scm:git:ssh://git@github.com:opentelecoms-org/jsmpp.git jsmpp-2.1.2/src/000077500000000000000000000000001246113105100134265ustar00rootroot00000000000000jsmpp-2.1.2/src/java/000077500000000000000000000000001246113105100143475ustar00rootroot00000000000000jsmpp-2.1.2/src/java/examples/000077500000000000000000000000001246113105100161655ustar00rootroot00000000000000jsmpp-2.1.2/src/java/examples/org/000077500000000000000000000000001246113105100167545ustar00rootroot00000000000000jsmpp-2.1.2/src/java/examples/org/jsmpp/000077500000000000000000000000001246113105100201055ustar00rootroot00000000000000jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/000077500000000000000000000000001246113105100217235ustar00rootroot00000000000000jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/AcceptingConnectionAndBindExample.java000066400000000000000000000055261246113105100312470ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples; import java.io.IOException; import java.util.concurrent.TimeoutException; import org.apache.log4j.BasicConfigurator; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.session.BindRequest; import org.jsmpp.session.SMPPServerSession; import org.jsmpp.session.SMPPServerSessionListener; /** * @author uudashr * */ public class AcceptingConnectionAndBindExample { public static void main(String[] args) { BasicConfigurator.configure(); try { System.out.println("Listening ..."); SMPPServerSessionListener sessionListener = new SMPPServerSessionListener(8056); // accepting connection, session still in OPEN state SMPPServerSession session = sessionListener.accept(); System.out.println("Accept connection"); try { BindRequest request = session.waitForBind(5000); System.out.println("Receive bind request"); if (request.getBindParameter().getSystemId().equals("test") && request.getBindParameter().getPassword().equals("test")) { // accepting request and send bind response immediately System.out.println("Accepting bind request"); request.accept("sys"); try { Thread.sleep(20000); } catch (InterruptedException e) {} } else { System.out.println("Rejecting bind request"); request.reject(SMPPConstant.STAT_ESME_RINVPASWD); } } catch (TimeoutException e) { System.out.println("No binding request made after 5000 millisecond"); e.printStackTrace(); } if (session.getSessionState().isBound()) { System.out.println("Closing session"); session.unbindAndClose(); } System.out.println("Closing session listener"); sessionListener.close(); } catch (PDUStringException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/AsyncSubmitReceiveDeliverSmExample.java000066400000000000000000000153551246113105100314720ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples; import java.io.IOException; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import org.apache.log4j.BasicConfigurator; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.bean.AlertNotification; import org.jsmpp.bean.Alphabet; import org.jsmpp.bean.BindType; import org.jsmpp.bean.DataSm; import org.jsmpp.bean.DeliverSm; import org.jsmpp.bean.DeliveryReceipt; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.GeneralDataCoding; import org.jsmpp.bean.MessageClass; import org.jsmpp.bean.MessageType; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.SMSCDeliveryReceipt; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.session.BindParameter; import org.jsmpp.session.DataSmResult; import org.jsmpp.session.MessageReceiverListener; import org.jsmpp.session.SMPPSession; import org.jsmpp.session.Session; import org.jsmpp.util.AbsoluteTimeFormatter; import org.jsmpp.util.InvalidDeliveryReceiptException; import org.jsmpp.util.TimeFormatter; /** * @author uudashr * */ public class AsyncSubmitReceiveDeliverSmExample { private static TimeFormatter timeFormatter = new AbsoluteTimeFormatter();; public static void main(String[] args) { final AtomicInteger counter = new AtomicInteger(); BasicConfigurator.configure(); final SMPPSession session = new SMPPSession(); try { session.connectAndBind("localhost", 8056, new BindParameter(BindType.BIND_TRX, "test", "test", "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 MessageReceiverListener() { public void onAcceptDeliverSm(DeliverSm deliverSm) throws ProcessRequestException { if (MessageType.SMSC_DEL_RECEIPT.containedIn(deliverSm.getEsmClass())) { counter.incrementAndGet(); // delivery receipt try { DeliveryReceipt delReceipt = deliverSm.getShortMessageAsDeliveryReceipt(); long id = Long.parseLong(delReceipt.getId()) & 0xffffffff; String messageId = Long.toString(id, 16).toUpperCase(); System.out.println("Receiving delivery receipt for message '" + messageId + "' : " + delReceipt); } catch (InvalidDeliveryReceiptException e) { System.err.println("Failed getting delivery receipt"); e.printStackTrace(); } } else { // regular short message System.out.println("Receiving message : " + new String(deliverSm.getShortMessage())); } } public DataSmResult onAcceptDataSm(DataSm dataSm, Session source) throws ProcessRequestException { // TODO Auto-generated method stub return null; } public void onAcceptAlertNotification( AlertNotification alertNotification) { } }); // Now we will send 50 message asynchronously with max outstanding messages 10. ExecutorService execService = Executors.newFixedThreadPool(10); // requesting delivery report final RegisteredDelivery registeredDelivery = new RegisteredDelivery(); registeredDelivery.setSMSCDeliveryReceipt(SMSCDeliveryReceipt.SUCCESS_FAILURE); final int maxMessage = 50; for (int i = 0; i < maxMessage; i++) { execService.execute(new Runnable() { public void run() { 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, registeredDelivery, (byte)0, new GeneralDataCoding(false, true, MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT), (byte)0, "jSMPP simplify SMPP on Java platform".getBytes()); System.out.println("Message submitted, message_id is " + messageId); } catch (PDUException e) { System.err.println("Invalid PDU parameter"); e.printStackTrace(); counter.incrementAndGet(); } catch (ResponseTimeoutException e) { System.err.println("Response timeout"); e.printStackTrace(); counter.incrementAndGet(); } catch (InvalidResponseException e) { // Invalid response System.err.println("Receive invalid respose"); e.printStackTrace(); counter.incrementAndGet(); } catch (NegativeResponseException e) { // Receiving negative response (non-zero command_status) System.err.println("Receive negative response"); e.printStackTrace(); counter.incrementAndGet(); } catch (IOException e) { System.err.println("IO error occur"); e.printStackTrace(); counter.incrementAndGet(); } } }); } while (counter.get() != maxMessage) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } session.unbindAndClose(); execService.shutdown(); } } jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/MessageReceiverListenerImpl.java000066400000000000000000000053531246113105100301750ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples; import org.jsmpp.bean.AlertNotification; import org.jsmpp.bean.DataSm; import org.jsmpp.bean.DeliverSm; import org.jsmpp.bean.DeliveryReceipt; import org.jsmpp.bean.MessageType; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.session.DataSmResult; import org.jsmpp.session.MessageReceiverListener; import org.jsmpp.session.Session; import org.jsmpp.util.InvalidDeliveryReceiptException; /** * @author uudashr * */ public class MessageReceiverListenerImpl implements MessageReceiverListener { public void onAcceptDeliverSm(DeliverSm deliverSm) throws ProcessRequestException { if (MessageType.SMSC_DEL_RECEIPT.containedIn(deliverSm.getEsmClass())) { // this message is delivery receipt try { DeliveryReceipt delReceipt = deliverSm.getShortMessageAsDeliveryReceipt(); // lets cover the id to hex string format long id = Long.parseLong(delReceipt.getId()) & 0xffffffff; String messageId = Long.toString(id, 16).toUpperCase(); /* * you can update the status of your submitted message on the * database based on messageId */ System.out.println("Receiving delivery receipt for message '" + messageId + " ' from " + deliverSm.getSourceAddr() + " to " + deliverSm.getDestAddress() + " : " + delReceipt); } catch (InvalidDeliveryReceiptException e) { System.err.println("Failed getting delivery receipt"); e.printStackTrace(); } } else { // this message is regular short message /* * you can save the incoming message to database. */ System.out.println("Receiving message : " + new String(deliverSm.getShortMessage())); } } public DataSmResult onAcceptDataSm(DataSm dataSm, Session source) throws ProcessRequestException { return null; }; public void onAcceptAlertNotification(AlertNotification alertNotification) { } } jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/OpenAndBindExample.java000066400000000000000000000032461246113105100262300ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples; import java.io.IOException; import org.apache.log4j.BasicConfigurator; import org.jsmpp.bean.BindType; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.session.BindParameter; import org.jsmpp.session.SMPPSession; /** * @author uudashr * */ public class OpenAndBindExample { public static void main(String[] args) { BasicConfigurator.configure(); String host = "localhost"; int port = 8056; SMPPSession session = new SMPPSession(); try { System.out.println("Connect and bind to " + host + " port " + port); session.connectAndBind(host, port, new BindParameter(BindType.BIND_TRX, "test", "test", "cp", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null)); } catch (IOException e) { // Failed connect and bind to SMSC System.err.println("Failed connect and bind to host"); e.printStackTrace(); } try { Thread.sleep(10000); } catch (InterruptedException e) {} session.unbindAndClose(); } } jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/ReceiveSubmittedMessageExample.java000066400000000000000000000127401246113105100306560ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples; import java.io.IOException; import java.util.concurrent.TimeoutException; import org.apache.log4j.BasicConfigurator; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.CancelSm; import org.jsmpp.bean.DataSm; import org.jsmpp.bean.QuerySm; import org.jsmpp.bean.ReplaceSm; import org.jsmpp.bean.SubmitMulti; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.SubmitSm; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.session.BindRequest; import org.jsmpp.session.DataSmResult; import org.jsmpp.session.QuerySmResult; import org.jsmpp.session.SMPPServerSession; import org.jsmpp.session.SMPPServerSessionListener; import org.jsmpp.session.ServerMessageReceiverListener; import org.jsmpp.session.Session; import org.jsmpp.util.MessageIDGenerator; import org.jsmpp.util.MessageId; import org.jsmpp.util.RandomMessageIDGenerator; /** * @author uudashr * */ public class ReceiveSubmittedMessageExample { public static void main(String[] args) { BasicConfigurator.configure(); try { // prepare generator of Message ID final MessageIDGenerator messageIdGenerator = new RandomMessageIDGenerator(); // prepare the message receiver ServerMessageReceiverListener messageReceiverListener = new ServerMessageReceiverListener() { public MessageId onAcceptSubmitSm(SubmitSm submitSm, SMPPServerSession source) throws ProcessRequestException { System.out.println("Receiving message : " + new String(submitSm.getShortMessage())); // need message_id to response submit_sm return messageIdGenerator.newMessageId(); } public QuerySmResult onAcceptQuerySm(QuerySm querySm, SMPPServerSession source) throws ProcessRequestException { return null; } public SubmitMultiResult onAcceptSubmitMulti( SubmitMulti submitMulti, SMPPServerSession source) throws ProcessRequestException { return null; } public DataSmResult onAcceptDataSm(DataSm dataSm, Session source) throws ProcessRequestException { return null; } public void onAcceptCancelSm(CancelSm cancelSm, SMPPServerSession source) throws ProcessRequestException { } public void onAcceptReplaceSm(ReplaceSm replaceSm, SMPPServerSession source) throws ProcessRequestException { } }; System.out.println("Listening ..."); SMPPServerSessionListener sessionListener = new SMPPServerSessionListener(8056); // set all default ServerMessageReceiverListener for all accepted SMPPServerSessionListener sessionListener.setMessageReceiverListener(messageReceiverListener); // accepting connection, session still in OPEN state SMPPServerSession session = sessionListener.accept(); // or we can set for each accepted session session.setMessageReceiverListener(messageReceiverListener) System.out.println("Accept connection"); try { BindRequest request = session.waitForBind(5000); System.out.println("Receive bind request"); if (request.getBindParameter().getSystemId().equals("test") && request.getBindParameter().getPassword().equals("test")) { // accepting request and send bind response immediately System.out.println("Accepting bind request"); request.accept("sys"); try { Thread.sleep(20000); } catch (InterruptedException e) {} } else { System.out.println("Rejecting bind request"); request.reject(SMPPConstant.STAT_ESME_RINVPASWD); } } catch (TimeoutException e) { System.out.println("No binding request made after 5000 millisecond"); e.printStackTrace(); } System.out.println("Closing session"); session.unbindAndClose(); System.out.println("Closing session listener"); sessionListener.close(); } catch (PDUStringException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/SMPPServerSimulator.java000066400000000000000000000211241246113105100264340ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples; import java.io.IOException; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeoutException; import org.apache.log4j.BasicConfigurator; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.CancelSm; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.DataSm; import org.jsmpp.bean.DeliveryReceipt; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.GSMSpecificFeature; import org.jsmpp.bean.MessageMode; import org.jsmpp.bean.MessageType; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.QuerySm; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.ReplaceSm; import org.jsmpp.bean.SMSCDeliveryReceipt; import org.jsmpp.bean.SubmitMulti; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.SubmitSm; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.session.BindRequest; import org.jsmpp.session.DataSmResult; import org.jsmpp.session.QuerySmResult; import org.jsmpp.session.SMPPServerSession; import org.jsmpp.session.SMPPServerSessionListener; import org.jsmpp.session.ServerMessageReceiverListener; import org.jsmpp.session.ServerResponseDeliveryAdapter; import org.jsmpp.session.Session; import org.jsmpp.util.DeliveryReceiptState; import org.jsmpp.util.MessageIDGenerator; import org.jsmpp.util.MessageId; import org.jsmpp.util.RandomMessageIDGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author uudashr * */ public class SMPPServerSimulator extends ServerResponseDeliveryAdapter implements Runnable, ServerMessageReceiverListener { private static final Integer DEFAULT_PORT = 8056; private static final Logger logger = LoggerFactory.getLogger(SMPPServerSimulator.class); private final ExecutorService execService = Executors.newFixedThreadPool(5); private final ExecutorService execServiceDelReciept = Executors.newFixedThreadPool(100); private final MessageIDGenerator messageIDGenerator = new RandomMessageIDGenerator(); private int port; public SMPPServerSimulator(int port) { this.port = port; } public void run() { try { SMPPServerSessionListener sessionListener = new SMPPServerSessionListener(port); logger.info("Listening on port {}", port); while (true) { SMPPServerSession serverSession = sessionListener.accept(); logger.info("Accepting connection for session {}", serverSession.getSessionId()); serverSession.setMessageReceiverListener(this); serverSession.setResponseDeliveryListener(this); execService.execute(new WaitBindTask(serverSession)); } } catch (IOException e) { logger.error("IO error occured", e); } } public QuerySmResult onAcceptQuerySm(QuerySm querySm, SMPPServerSession source) throws ProcessRequestException { logger.info("Accepting query sm, but not implemented"); return null; } public MessageId onAcceptSubmitSm(SubmitSm submitSm, SMPPServerSession source) throws ProcessRequestException { MessageId messageId = messageIDGenerator.newMessageId(); logger.debug("Receiving submit_sm {}, and return message id {}", new String(submitSm.getShortMessage()), messageId.getValue()); if (SMSCDeliveryReceipt.SUCCESS.containedIn(submitSm.getRegisteredDelivery()) || SMSCDeliveryReceipt.SUCCESS_FAILURE.containedIn(submitSm.getRegisteredDelivery())) { execServiceDelReciept.execute(new DeliveryReceiptTask(source, submitSm, messageId)); } return messageId; } public void onSubmitSmRespSent(MessageId messageId, SMPPServerSession source) { logger.debug("submit_sm_resp with message_id {} has been sent", messageId); } public SubmitMultiResult onAcceptSubmitMulti(SubmitMulti submitMulti, SMPPServerSession source) throws ProcessRequestException { return null; } public DataSmResult onAcceptDataSm(DataSm dataSm, Session source) throws ProcessRequestException { return null; } public void onAcceptCancelSm(CancelSm cancelSm, SMPPServerSession source) throws ProcessRequestException { } public void onAcceptReplaceSm(ReplaceSm replaceSm, SMPPServerSession source) throws ProcessRequestException { } private class WaitBindTask implements Runnable { private final SMPPServerSession serverSession; public WaitBindTask(SMPPServerSession serverSession) { this.serverSession = serverSession; } public void run() { try { BindRequest bindRequest = serverSession.waitForBind(1000); logger.info("Accepting bind for session {}", serverSession.getSessionId()); try { bindRequest.accept("sys"); } catch (PDUStringException e) { logger.error("Invalid system id", e); bindRequest.reject(SMPPConstant.STAT_ESME_RSYSERR); } } catch (IllegalStateException e) { logger.error("System error", e); } catch (TimeoutException e) { logger.warn("Wait for bind has reach timeout", e); } catch (IOException e) { logger.error("Failed accepting bind request for session {}", serverSession.getSessionId()); } } } private class DeliveryReceiptTask implements Runnable { private final SMPPServerSession session; private final SubmitSm submitSm; private MessageId messageId; public DeliveryReceiptTask(SMPPServerSession session, SubmitSm submitSm, MessageId messageId) { this.session = session; this.submitSm = submitSm; this.messageId = messageId; } public void run() { try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } String stringValue = Integer.valueOf(messageId.getValue(), 16).toString(); try { DeliveryReceipt delRec = new DeliveryReceipt(stringValue, 1, 1, new Date(), new Date(), DeliveryReceiptState.DELIVRD, null, new String(submitSm.getShortMessage())); session.deliverShortMessage( "mc", TypeOfNumber.valueOf(submitSm.getDestAddrTon()), NumberingPlanIndicator.valueOf(submitSm.getDestAddrNpi()), submitSm.getDestAddress(), TypeOfNumber.valueOf(submitSm.getSourceAddrTon()), NumberingPlanIndicator.valueOf(submitSm.getSourceAddrNpi()), submitSm.getSourceAddr(), new ESMClass(MessageMode.DEFAULT, MessageType.SMSC_DEL_RECEIPT, GSMSpecificFeature.DEFAULT), (byte)0, (byte)0, new RegisteredDelivery(0), DataCoding.newInstance(0), delRec.toString().getBytes()); logger.debug("Sending delivery reciept for message id " + messageId + ":" + stringValue); } catch (Exception e) { logger.error("Failed sending delivery_receipt for message id " + messageId + ":" + stringValue, e); } } } public static void main(String[] args) { int port; try { port = Integer.parseInt(System.getProperty("jsmpp.simulator.port", DEFAULT_PORT.toString())); } catch (NumberFormatException e) { port = DEFAULT_PORT; } BasicConfigurator.configure(); SMPPServerSimulator smppServerSim = new SMPPServerSimulator(port); smppServerSim.run(); } } jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/SimpleSubmitExample.java000066400000000000000000000064731246113105100265310ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples; import java.io.IOException; import java.util.Date; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.bean.Alphabet; import org.jsmpp.bean.BindType; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.GeneralDataCoding; import org.jsmpp.bean.MessageClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.SMSCDeliveryReceipt; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.session.BindParameter; import org.jsmpp.session.SMPPSession; import org.jsmpp.util.AbsoluteTimeFormatter; import org.jsmpp.util.TimeFormatter; /** * @author uudashr * */ public class SimpleSubmitExample { private static TimeFormatter timeFormatter = new AbsoluteTimeFormatter();; public static void main(String[] args) { SMPPSession session = new SMPPSession(); try { session.connectAndBind("localhost", 8056, new BindParameter(BindType.BIND_TX, "test", "test", "cp", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null)); } catch (IOException e) { System.err.println("Failed connect and bind to host"); e.printStackTrace(); } 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.DEFAULT), (byte)0, new GeneralDataCoding(false, true, MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT), (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(); } } jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/SimpleSubmitRegisteredExample.java000066400000000000000000000071141246113105100305400ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples; import java.io.IOException; import java.util.Date; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.bean.Alphabet; import org.jsmpp.bean.BindType; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.GeneralDataCoding; import org.jsmpp.bean.MessageClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.SMSCDeliveryReceipt; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.session.BindParameter; import org.jsmpp.session.SMPPSession; import org.jsmpp.util.AbsoluteTimeFormatter; import org.jsmpp.util.TimeFormatter; /** * @author uudashr * */ public class SimpleSubmitRegisteredExample { private static TimeFormatter timeFormatter = new AbsoluteTimeFormatter();; public static void main(String[] args) { SMPPSession session = new SMPPSession(); try { session.connectAndBind("localhost", 8056, new BindParameter(BindType.BIND_TRX, "test", "test", "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, new GeneralDataCoding(false, true, MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT), (byte)0, "jSMPP simplify SMPP on Java platform".getBytes()); /* * you can save the submitted message to database. */ 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(); } } jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/StressClient.java000066400000000000000000000270271246113105100252200ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.log4j.PropertyConfigurator; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.PDUStringException; import org.jsmpp.bean.Alphabet; import org.jsmpp.bean.BindType; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.GeneralDataCoding; import org.jsmpp.bean.MessageClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.session.SMPPSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This stress client is an example of submit bulk messages asynchronously. * * * * * * * * * * * * * * *
NameDescriptionDefault value
jsmpp.client.hostServer host addresslocalhost
jsmpp.client.portServer port8056
jsmpp.client.systemIdSystem Identifierj
jsmpp.client.passwordPasswordjpwd
jsmpp.client.sourceAddrSubmit Source Address1616
jsmpp.client.destinationAddrSubmit Destination Address62161616
jsmpp.client.transactionTimerTransaction timer2000
jsmpp.client.bulkSizeAmount of bulk messages100000
jsmpp.client.procDegreeMax parallel processor for PDU reading3
jsmpp.client.maxOutstandingMaximum outstanding messages10
jsmpp.client.log4jPathLog4j configurationconf/client-log4j.properties
* @author uudashr * */ public class StressClient implements Runnable { private static final String DEFAULT_PASSWORD = "jpwd"; private static final String DEFAULT_SYSID = "j"; private static final String DEFAULT_DESTADDR = "62161616"; private static final String DEFAULT_SOURCEADDR = "1616"; private static final Logger logger = LoggerFactory.getLogger(StressClient.class); private static final String DEFAULT_LOG4J_PATH = "stress/client-log4j.properties"; private static final String DEFAULT_HOST = "localhost"; private static final Integer DEFAULT_PORT = 8056; private static final Long DEFAULT_TRANSACTIONTIMER = 2000L; private static final Integer DEFAULT_BULK_SIZE = 100000; private static final Integer DEFAULT_PROCESSOR_DEGREE = 3; private static final Integer DEFAULT_MAX_OUTSTANDING = 10; private AtomicInteger requestCounter = new AtomicInteger(); private AtomicInteger totalRequestCounter = new AtomicInteger(); private AtomicInteger responseCounter = new AtomicInteger(); private AtomicInteger totalResponseCounter = new AtomicInteger(); private AtomicLong maxDelay = new AtomicLong(); private ExecutorService execService; private String host; private int port; private int bulkSize; private SMPPSession smppSession = new SMPPSession(); private AtomicBoolean exit = new AtomicBoolean(); private int id; private String systemId; private String password; private String sourceAddr; private String destinationAddr; public StressClient(int id, String host, int port, int bulkSize, String systemId, String password, String sourceAddr, String destinationAddr, long transactionTimer, int pduProcessorDegree, int maxOutstanding) { this.id = id; this.host = host; this.port = port; this.bulkSize = bulkSize; this.systemId = systemId; this.password = password; this.sourceAddr = sourceAddr; this.destinationAddr = destinationAddr; smppSession.setPduProcessorDegree(pduProcessorDegree); smppSession.setTransactionTimer(transactionTimer); execService = Executors.newFixedThreadPool(maxOutstanding); } private void shutdown() { execService.shutdown(); exit.set(true); } public void run() { try { smppSession.connectAndBind(host, port, BindType.BIND_TRX, systemId, password, "cln", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null); logger.info("Bound to " + host + ":" + port); } catch (IOException e) { logger.error("Failed initialize connection or bind", e); return; } new TrafficWatcherThread().start(); logger.info("Starting send " + bulkSize + " bulk message..."); for (int i = 0; i < bulkSize && !exit.get(); i++) { execService.execute(newSendTask("Hello " + id + " idx=" + i)); } while (!exit.get()) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } logger.info("Done"); smppSession.unbindAndClose(); } private Runnable newSendTask(final String message) { return new Runnable() { public void run() { try { requestCounter.incrementAndGet(); long startTime = System.currentTimeMillis(); smppSession.submitShortMessage(null, TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, sourceAddr, TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, destinationAddr, new ESMClass(), (byte)0, (byte)0, null, null, new RegisteredDelivery(0), (byte)0, new GeneralDataCoding(true, true, MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT), (byte)0, message.getBytes()); long delay = System.currentTimeMillis() - startTime; responseCounter.incrementAndGet(); if (maxDelay.get() < delay) { maxDelay.set(delay); } } catch (PDUException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } catch (ResponseTimeoutException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } catch (InvalidResponseException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } catch (NegativeResponseException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } catch (IOException e) { logger.error("Failed submit short message '" + message + "'", e); shutdown(); } } }; } private class TrafficWatcherThread extends Thread { @Override public void run() { logger.info("Starting traffic watcher..."); while (!exit.get()) { try { Thread.sleep(1000); } catch (InterruptedException e) { } int requestPerSecond = requestCounter.getAndSet(0); int responsePerSecond = responseCounter.getAndSet(0); long maxDelayPerSecond = maxDelay.getAndSet(0); totalRequestCounter.addAndGet(requestPerSecond); int total = totalResponseCounter.addAndGet(responsePerSecond); logger.info("Request/Response per second : " + requestPerSecond + "/" + responsePerSecond + " of " + total + " maxDelay=" + maxDelayPerSecond); if (total == bulkSize) { shutdown(); } } } } public static void main(String[] args) { String host = System.getProperty("jsmpp.client.host", DEFAULT_HOST); String systemId = System.getProperty("jsmpp.client.systemId", DEFAULT_SYSID); String password = System.getProperty("jsmpp.client.password", DEFAULT_PASSWORD); String sourceAddr = System.getProperty("jsmpp.client.sourceAddr", DEFAULT_SOURCEADDR); String destinationAddr = System.getProperty("jsmpp.client.destinationAddr", DEFAULT_DESTADDR); int port; try { port = Integer.parseInt(System.getProperty("jsmpp.client.port", DEFAULT_PORT.toString())); } catch (NumberFormatException e) { port = DEFAULT_PORT; } long transactionTimer; try { transactionTimer = Integer.parseInt(System.getProperty("jsmpp.client.transactionTimer", DEFAULT_TRANSACTIONTIMER.toString())); } catch (NumberFormatException e) { transactionTimer = DEFAULT_TRANSACTIONTIMER; } int bulkSize; try { bulkSize = Integer.parseInt(System.getProperty("jsmpp.client.bulkSize", DEFAULT_BULK_SIZE.toString())); } catch (NumberFormatException e) { bulkSize = DEFAULT_BULK_SIZE; } int processorDegree; try { processorDegree = Integer.parseInt(System.getProperty("jsmpp.client.procDegree", DEFAULT_PROCESSOR_DEGREE.toString())); } catch (NumberFormatException e) { processorDegree = DEFAULT_PROCESSOR_DEGREE; } int maxOutstanding; try { maxOutstanding = Integer.parseInt(System.getProperty("jsmpp.client.maxOutstanding", DEFAULT_MAX_OUTSTANDING.toString())); } catch (NumberFormatException e) { maxOutstanding = DEFAULT_MAX_OUTSTANDING; } String log4jPath = System.getProperty("jsmpp.client.log4jPath", DEFAULT_LOG4J_PATH); PropertyConfigurator.configure(log4jPath); logger.info("Target server {}:{}", host, port); logger.info("System ID: {}", systemId); logger.info("Password: {}", password); logger.info("Source address: {}", sourceAddr); logger.info("Destination address: {}", destinationAddr); logger.info("Transaction timer: {}", transactionTimer); logger.info("Bulk size: {}", bulkSize); logger.info("Max outstanding: {}", maxOutstanding); logger.info("Processor degree: {}", processorDegree); StressClient stressClient = new StressClient(0, host, port, bulkSize, systemId, password, sourceAddr, destinationAddr, transactionTimer, processorDegree, maxOutstanding); stressClient.run(); } } jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/StressServer.java000066400000000000000000000235001246113105100252400ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples; import java.io.IOException; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import org.apache.log4j.PropertyConfigurator; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.CancelSm; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.DataSm; import org.jsmpp.bean.DeliveryReceipt; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.GSMSpecificFeature; import org.jsmpp.bean.MessageMode; import org.jsmpp.bean.MessageType; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.QuerySm; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.ReplaceSm; import org.jsmpp.bean.SubmitMulti; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.SubmitSm; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.extra.SessionState; import org.jsmpp.session.BindRequest; import org.jsmpp.session.DataSmResult; import org.jsmpp.session.QuerySmResult; import org.jsmpp.session.SMPPServerSession; import org.jsmpp.session.SMPPServerSessionListener; import org.jsmpp.session.ServerMessageReceiverListener; import org.jsmpp.session.Session; import org.jsmpp.session.SessionStateListener; import org.jsmpp.util.DeliveryReceiptState; import org.jsmpp.util.MessageIDGenerator; import org.jsmpp.util.MessageId; import org.jsmpp.util.RandomMessageIDGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author uudashr * */ public class StressServer implements Runnable, ServerMessageReceiverListener { private static final int DEFAULT_MAX_WAIT_BIND = 10; private static final String DEFAULT_LOG4J_PATH = "stress/server-log4j.properties"; private static final Integer DEFAULT_PORT = 8056; private static final Integer DEFAULT_PROCESSOR_DEGREE = 3; private static final Logger logger = LoggerFactory.getLogger(StressServer.class); private final ExecutorService waitBindExecService = Executors.newFixedThreadPool(DEFAULT_MAX_WAIT_BIND); private final MessageIDGenerator messageIDGenerator = new RandomMessageIDGenerator(); private final AtomicInteger requestCounter = new AtomicInteger(); private int processorDegree; private int port; public StressServer(int port, int processorDegree) { this.port = port; this.processorDegree = processorDegree; } public void run() { try { SMPPServerSessionListener sessionListener = new SMPPServerSessionListener(port); sessionListener.setSessionStateListener(new SessionStateListenerImpl()); sessionListener.setPduProcessorDegree(processorDegree); new TrafficWatcherThread().start(); logger.info("Listening on port {}", port); while (true) { SMPPServerSession serverSession = sessionListener.accept(); logger.info("Accepting connection for session {}", serverSession.getSessionId()); serverSession.setMessageReceiverListener(this); waitBindExecService.execute(new WaitBindTask(serverSession)); } } catch (IOException e) { logger.error("IO error occured", e); } } public QuerySmResult onAcceptQuerySm(QuerySm querySm, SMPPServerSession source) throws ProcessRequestException { return null; } public MessageId onAcceptSubmitSm(SubmitSm submitSm, SMPPServerSession source) throws ProcessRequestException { MessageId messageId = messageIDGenerator.newMessageId(); logger.debug("Receiving submit_sm {}, and return message id {}", new String(submitSm.getShortMessage()), messageId.getValue()); requestCounter.incrementAndGet(); return messageId; } public SubmitMultiResult onAcceptSubmitMulti(SubmitMulti submitMulti, SMPPServerSession source) throws ProcessRequestException { return null; } public DataSmResult onAcceptDataSm(DataSm dataSm, Session source) throws ProcessRequestException { return null; } public void onAcceptCancelSm(CancelSm cancelSm, SMPPServerSession source) throws ProcessRequestException { } public void onAcceptReplaceSm(ReplaceSm replaceSm, SMPPServerSession source) throws ProcessRequestException { } private class SessionStateListenerImpl implements SessionStateListener { public void onStateChange(SessionState newState, SessionState oldState, Object source) { SMPPServerSession session = (SMPPServerSession)source; logger.info("New state of " + session.getSessionId() + " is " + newState); } } private class WaitBindTask implements Runnable { private final SMPPServerSession serverSession; public WaitBindTask(SMPPServerSession serverSession) { this.serverSession = serverSession; } public void run() { try { BindRequest bindRequest = serverSession.waitForBind(1000); logger.debug("Accepting bind for session {}", serverSession.getSessionId()); try { bindRequest.accept("sys"); } catch (PDUStringException e) { logger.error("Invalid system id", e); bindRequest.reject(SMPPConstant.STAT_ESME_RSYSERR); } } catch (IllegalStateException e) { logger.error("System error", e); } catch (TimeoutException e) { logger.warn("Wait for bind has reach timeout", e); } catch (IOException e) { logger.error("Failed accepting bind request for session {}", serverSession.getSessionId()); } } } private class DeliveryReceiptTask implements Runnable { private final SMPPServerSession session; private final SubmitSm submitSm; private MessageId messageId; public DeliveryReceiptTask(SMPPServerSession session, SubmitSm submitSm, MessageId messageId) { this.session = session; this.submitSm = submitSm; this.messageId = messageId; } public void run() { try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } String stringValue = Integer.valueOf(messageId.getValue(), 16).toString(); try { DeliveryReceipt delRec = new DeliveryReceipt(stringValue, 1, 1, new Date(), new Date(), DeliveryReceiptState.DELIVRD, null, new String(submitSm.getShortMessage())); session.deliverShortMessage( "mc", TypeOfNumber.valueOf(submitSm.getDestAddrTon()), NumberingPlanIndicator.valueOf(submitSm.getDestAddrNpi()), submitSm.getDestAddress(), TypeOfNumber.valueOf(submitSm.getSourceAddrTon()), NumberingPlanIndicator.valueOf(submitSm.getSourceAddrNpi()), submitSm.getSourceAddr(), new ESMClass(MessageMode.DEFAULT, MessageType.SMSC_DEL_RECEIPT, GSMSpecificFeature.DEFAULT), (byte)0, (byte)0, new RegisteredDelivery(0), DataCoding.newInstance(0), delRec.toString().getBytes()); logger.debug("Sending delivery reciept for message id " + messageId + ":" + stringValue); } catch (Exception e) { logger.error("Failed sending delivery_receipt for message id " + messageId + ":" + stringValue, e); } } } private class TrafficWatcherThread extends Thread { @Override public void run() { logger.info("Starting traffic watcher..."); while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { } int trafficPerSecond = requestCounter.getAndSet(0); logger.info("Traffic per second : " + trafficPerSecond); } } } public static void main(String[] args) { int port; try { port = Integer.parseInt(System.getProperty("jsmpp.server.port", DEFAULT_PORT.toString())); } catch (NumberFormatException e) { port = DEFAULT_PORT; } int processorDegree; try { processorDegree = Integer.parseInt(System.getProperty("jsmpp.server.procDegree", DEFAULT_PROCESSOR_DEGREE.toString())); } catch (NumberFormatException e) { processorDegree = DEFAULT_PROCESSOR_DEGREE; } String log4jPath = System.getProperty("jsmpp.server.log4jPath", DEFAULT_LOG4J_PATH); PropertyConfigurator.configure(log4jPath); logger.info("Processor degree: " + processorDegree); StressServer stressServer = new StressServer(port, processorDegree); stressServer.run(); } } jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/SubmitLongMessageExample.java000066400000000000000000000105241246113105100274740ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples; import java.io.IOException; import java.util.Date; import java.util.Random; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.bean.Alphabet; import org.jsmpp.bean.BindType; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.GeneralDataCoding; import org.jsmpp.bean.MessageClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.OptionalParameters; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.SMSCDeliveryReceipt; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.session.BindParameter; import org.jsmpp.session.SMPPSession; import org.jsmpp.util.AbsoluteTimeFormatter; import org.jsmpp.util.TimeFormatter; /** * @author uudashr * */ public class SubmitLongMessageExample { private static TimeFormatter timeFormatter = new AbsoluteTimeFormatter();; public static void main(String[] args) { SMPPSession session = new SMPPSession(); try { session.connectAndBind("localhost", 8056, new BindParameter(BindType.BIND_TX, "test", "test", "cp", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null)); } catch (IOException e) { System.err.println("Failed connect and bind to host"); e.printStackTrace(); } Random random = new Random(); final int totalSegments = 3; OptionalParameter sarMsgRefNum = OptionalParameters.newSarMsgRefNum((short)random.nextInt()); OptionalParameter sarTotalSegments = OptionalParameters.newSarTotalSegments(totalSegments); for (int i = 0; i < totalSegments; i++) { final int seqNum = i + 1; String message = "Message part " + seqNum + " of " + totalSegments + " "; OptionalParameter sarSegmentSeqnum = OptionalParameters.newSarSegmentSeqnum(seqNum); String messageId = submitMessage(session, message, sarMsgRefNum, sarSegmentSeqnum, sarTotalSegments); System.out.println("Message submitted, message_id is " + messageId); } session.unbindAndClose(); } public static String submitMessage(SMPPSession session, String message, OptionalParameter sarMsgRefNum, OptionalParameter sarSegmentSeqnum, OptionalParameter sarTotalSegments) { String messageId = null; try { 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.DEFAULT), (byte)0, new GeneralDataCoding(false, true, MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT), (byte)0, message.getBytes(), sarMsgRefNum, sarSegmentSeqnum, sarTotalSegments);; } 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(); } return messageId; } } jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/gateway/000077500000000000000000000000001246113105100233645ustar00rootroot00000000000000jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/gateway/AutoReconnectGateway.java000066400000000000000000000164311246113105100303270ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples.gateway; import java.io.IOException; import org.apache.log4j.BasicConfigurator; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.bean.BindType; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.extra.SessionState; import org.jsmpp.session.BindParameter; import org.jsmpp.session.SMPPSession; import org.jsmpp.session.SessionStateListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This are implementation of {@link Gateway}. This gateway will reconnect for a * specified interval if the session are closed. * * @author uudashr * */ public class AutoReconnectGateway implements Gateway { private static final Logger logger = LoggerFactory.getLogger(AutoReconnectGateway.class); private SMPPSession session = null; private String remoteIpAddress; private int remotePort; private BindParameter bindParam; private long reconnectInterval = 5000L; // 5 seconds /** * Construct auto reconnect gateway with specified ip address, port and SMPP * Bind parameters. * * @param remoteIpAddress is the SMSC IP address. * @param remotePort is the SMSC port. * @param bindParam is the SMPP Bind parameters. * @throws IOException */ public AutoReconnectGateway(String remoteIpAddress, int remotePort, BindParameter bindParam) throws IOException { this.remoteIpAddress = remoteIpAddress; this.remotePort = remotePort; this.bindParam = bindParam; session = newSession(); } /* (non-Javadoc) * @see org.jsmpp.examples.gateway.Gateway#submitShortMessage(java.lang.String, org.jsmpp.bean.TypeOfNumber, org.jsmpp.bean.NumberingPlanIndicator, java.lang.String, org.jsmpp.bean.TypeOfNumber, org.jsmpp.bean.NumberingPlanIndicator, java.lang.String, org.jsmpp.bean.ESMClass, byte, byte, java.lang.String, java.lang.String, org.jsmpp.bean.RegisteredDelivery, byte, org.jsmpp.bean.DataCoding, byte, byte[], org.jsmpp.bean.OptionalParameter[]) */ public String submitShortMessage(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { return getSession().submitShortMessage(serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, protocolId, priorityFlag, scheduleDeliveryTime, validityPeriod, registeredDelivery, replaceIfPresentFlag, dataCoding, smDefaultMsgId, shortMessage, optionalParameters); } /** * Create new {@link SMPPSession} complete with the * {@link SessionStateListenerImpl}. * * @return the {@link SMPPSession}. * @throws IOException if the creation of new session failed. */ private SMPPSession newSession() throws IOException { SMPPSession tmpSession = new SMPPSession(remoteIpAddress, remotePort, bindParam); tmpSession.addSessionStateListener(new SessionStateListenerImpl()); return tmpSession; } /** * Get the session. If the session still null or not in bound state, then IO * exception will be thrown. * * @return the valid session. * @throws IOException if there is no valid session or session creation is * invalid. */ private SMPPSession getSession() throws IOException { if (session == null) { logger.info("Initiate session for the first time to " + remoteIpAddress + ":" + remotePort); session = newSession(); } else if (!session.getSessionState().isBound()) { throw new IOException("We have no valid session yet"); } return session; } /** * Reconnect session after specified interval. * * @param timeInMillis is the interval. */ private void reconnectAfter(final long timeInMillis) { new Thread() { @Override public void run() { logger.info("Schedule reconnect after " + timeInMillis + " millis"); try { Thread.sleep(timeInMillis); } catch (InterruptedException e) { } int attempt = 0; while (session == null || session.getSessionState().equals(SessionState.CLOSED)) { try { logger.info("Reconnecting attempt #" + (++attempt) + "..."); session = newSession(); } catch (IOException e) { logger.error("Failed opening connection and bind to " + remoteIpAddress + ":" + remotePort, e); // wait for a second try { Thread.sleep(1000); } catch (InterruptedException ee) {} } } } }.start(); } /** * This class will receive the notification from {@link SMPPSession} for the * state changes. It will schedule to re-initialize session. * * @author uudashr * */ private class SessionStateListenerImpl implements SessionStateListener { public void onStateChange(SessionState newState, SessionState oldState, Object source) { if (newState.equals(SessionState.CLOSED)) { logger.info("Session closed"); reconnectAfter(reconnectInterval); } } } public static void main(String[] args) throws IOException { BasicConfigurator.configure(); Gateway gateway = new AutoReconnectGateway("localhost", 8056, new BindParameter(BindType.BIND_TRX, "sms", "sms", "sms", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.ISDN, "8080")); while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) {} } } } jsmpp-2.1.2/src/java/examples/org/jsmpp/examples/gateway/Gateway.java000066400000000000000000000056361246113105100256420ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples.gateway; import java.io.IOException; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.session.SMPPSession; /** * This is a gateway to submit short message. * * @author uudashr * */ public interface Gateway { /** * Submit the short message. It has the same parameter as * {@link SMPPSession#submitShortMessage(String, TypeOfNumber, NumberingPlanIndicator, String, TypeOfNumber, NumberingPlanIndicator, String, ESMClass, byte, byte, String, String, RegisteredDelivery, byte, DataCoding, byte, byte[], OptionalParameter...)}. * * @param serviceType * @param sourceAddrTon * @param sourceAddrNpi * @param sourceAddr * @param destAddrTon * @param destAddrNpi * @param destinationAddr * @param esmClass * @param protocolId * @param priorityFlag * @param scheduleDeliveryTime * @param validityPeriod * @param registeredDelivery * @param replaceIfPresentFlag * @param dataCoding * @param smDefaultMsgId * @param shortMessage * @param optionalParameters * @return * @throws PDUException * @throws ResponseTimeoutException * @throws InvalidResponseException * @throws NegativeResponseException * @throws IOException */ public String submitShortMessage(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; } jsmpp-2.1.2/src/java/tests/000077500000000000000000000000001246113105100155115ustar00rootroot00000000000000jsmpp-2.1.2/src/java/tests/org/000077500000000000000000000000001246113105100163005ustar00rootroot00000000000000jsmpp-2.1.2/src/java/tests/org/jsmpp/000077500000000000000000000000001246113105100174315ustar00rootroot00000000000000jsmpp-2.1.2/src/java/tests/org/jsmpp/bean/000077500000000000000000000000001246113105100203365ustar00rootroot00000000000000jsmpp-2.1.2/src/java/tests/org/jsmpp/bean/DataCodingTest.java000066400000000000000000000054071246113105100240440ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import static org.testng.Assert.*; import org.testng.annotations.Test; /** * @author uudashr * */ public class DataCodingTest { @Test(groups="checkintest") public void testGeneralDataCoding() { GeneralDataCoding dataCoding = new GeneralDataCoding(); dataCoding.setCompressed(true); assertTrue(dataCoding.isCompressed()); dataCoding.setCompressed(false); assertFalse(dataCoding.isCompressed()); dataCoding.setContainMessageClass(true); assertTrue(dataCoding.isContainMessageClass()); dataCoding.setContainMessageClass(false); assertFalse(dataCoding.isContainMessageClass()); dataCoding.setContainMessageClass(true); dataCoding.setMessageClass(MessageClass.CLASS0); assertEquals(dataCoding.getMessageClass(), MessageClass.CLASS0); dataCoding.setMessageClass(MessageClass.CLASS1); assertEquals(dataCoding.getMessageClass(), MessageClass.CLASS1); dataCoding.setMessageClass(MessageClass.CLASS2); assertEquals(dataCoding.getMessageClass(), MessageClass.CLASS2); dataCoding.setMessageClass(MessageClass.CLASS3); assertEquals(dataCoding.getMessageClass(), MessageClass.CLASS3); dataCoding.setAlphabet(Alphabet.ALPHA_DEFAULT); assertEquals(dataCoding.getAlphabet(), Alphabet.ALPHA_DEFAULT); dataCoding.setAlphabet(Alphabet.ALPHA_8_BIT); assertEquals(dataCoding.getAlphabet(), Alphabet.ALPHA_8_BIT); dataCoding.setAlphabet(Alphabet.ALPHA_UCS2); assertEquals(dataCoding.getAlphabet(), Alphabet.ALPHA_UCS2); dataCoding.setAlphabet(Alphabet.ALPHA_RESERVED); assertEquals(dataCoding.getAlphabet(), Alphabet.ALPHA_RESERVED); assertTrue(GeneralDataCoding.isCompatible(dataCoding.value())); assertFalse(GeneralDataCoding.isCompatible((byte)0xff)); } @Test(groups="checkintest") public void testDataCoding0x1() { byte value = (byte)0x11; DataCoding dataCoding = DataCoding.newInstance(value); assertTrue(dataCoding instanceof GeneralDataCoding); GeneralDataCoding coding = (GeneralDataCoding)dataCoding; assertFalse(coding.isCompressed()); assertTrue(coding.isContainMessageClass()); assertEquals(coding.getAlphabet(), Alphabet.ALPHA_DEFAULT); assertEquals(coding.getMessageClass(), MessageClass.CLASS1); } } jsmpp-2.1.2/src/java/tests/org/jsmpp/bean/ESMClassTest.java000066400000000000000000000025661246113105100234640ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import static org.testng.Assert.*; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** * @author uudashr * */ public class ESMClassTest { private ESMClass esmClass; @BeforeTest public void setUp() { esmClass = new ESMClass(); } @Test(groups="checkintest") public void testSpecificFeature() { assertTrue(GSMSpecificFeature.DEFAULT.containedIn(esmClass)); esmClass.setSpecificFeature(GSMSpecificFeature.UDHI); assertTrue(GSMSpecificFeature.UDHI.containedIn(esmClass)); } @Test(groups="checkintest") public void testMessageType() { assertTrue(MessageType.DEFAULT.containedIn(esmClass)); esmClass.setMessageType(MessageType.SMSC_DEL_RECEIPT); assertTrue(MessageType.SMSC_DEL_RECEIPT.containedIn(esmClass)); } } jsmpp-2.1.2/src/java/tests/org/jsmpp/bean/OptionalParameterTest.java000066400000000000000000000051501246113105100254700ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import org.jsmpp.bean.OptionalParameter.OctetString; import org.jsmpp.bean.OptionalParameter.Tag; import org.jsmpp.util.OctetUtil; import org.testng.annotations.Test; /** * Test case for Optional Parameter. * * @author mikko.koponen * @author uudashr * */ public class OptionalParameterTest { @Test(groups="checkintest") public void stringParameterSerialization() { OptionalParameter param = new OptionalParameter.OctetString(Tag.DEST_SUBADDRESS, "jeah"); byte[] serialised = param.serialize(); assertEquals(serialised.length, 2 + 2 + 4); assertEquals(OctetUtil.bytesToShort(serialised, 0), Tag.DEST_SUBADDRESS.code()); assertEquals(OctetUtil.bytesToShort(serialised, 2), "jeah".getBytes().length); assertEquals(new String(serialised, 4, serialised.length - 4), "jeah"); } @Test(groups="checkintest") public void stringParameterDeserialization() { OptionalParameter param = OptionalParameters.deserialize(Tag.DEST_SUBADDRESS.code(), "jeah".getBytes()); assertTrue(param instanceof OptionalParameter.OctetString); OptionalParameter.OctetString stringParam = (OctetString) param; assertEquals(stringParam.getValueAsString(), "jeah"); } @Test public void undefinedTag() { final short tagCode = 0x0000; try { Tag.valueOf(tagCode); fail("Tag code 0x0000 should be not found"); } catch (IllegalArgumentException e) { } OptionalParameters.deserialize(tagCode, "Undefined tag".getBytes()); } @Test public void anotherUndefinedTag() { short tagCode = (short)(-127 & 0xffff); try { Tag.valueOf(tagCode); fail("Tag code " + tagCode + " should be not found"); } catch (IllegalArgumentException e) { } OptionalParameters.deserialize(tagCode, "Undefined tag".getBytes()); } }jsmpp-2.1.2/src/java/tests/org/jsmpp/bean/RegisteredDeliveryTest.java000066400000000000000000000022661246113105100256500ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import static org.testng.Assert.*; import org.testng.annotations.Test; /** * @author uudashr * */ public class RegisteredDeliveryTest { @Test(groups="checkintest") public void testSMSCDeliveryReceipt() { RegisteredDelivery regDel = new RegisteredDelivery(); assertTrue(SMSCDeliveryReceipt.DEFAULT.containedIn(regDel)); regDel.setSMSCDeliveryReceipt(SMSCDeliveryReceipt.SUCCESS_FAILURE); assertTrue(SMSCDeliveryReceipt.SUCCESS_FAILURE.containedIn(regDel)); regDel.setSMSCDeliveryReceipt(SMSCDeliveryReceipt.SUCCESS); assertTrue(SMSCDeliveryReceipt.SUCCESS.containedIn(regDel)); } } jsmpp-2.1.2/src/java/tests/org/jsmpp/bean/ReplaceIfPresentFlagTest.java000066400000000000000000000016661246113105100260370ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import static org.testng.Assert.*; import org.testng.annotations.Test; /** * @author uudashr * */ public class ReplaceIfPresentFlagTest { @Test(groups="checkintest") public void testEquality() { ReplaceIfPresentFlag replaceIfPresentFlag = new ReplaceIfPresentFlag(1); assertEquals(replaceIfPresentFlag, new ReplaceIfPresentFlag(1)); } } jsmpp-2.1.2/src/java/tests/org/jsmpp/bean/StringValidationTest.java000066400000000000000000000044131246113105100253240ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.PDUStringException; import org.jsmpp.util.StringParameter; import org.jsmpp.util.StringValidator; import static org.testng.Assert.*; import org.testng.annotations.Test; /** * Test case of string validation. * @author uudashr * @version 1.0 * */ public class StringValidationTest { @Test(groups="checkintest") public void testValidation() { try { StringValidator.validateString("", StringParameter.SYSTEM_ID); } catch (PDUStringException e) { fail("Should be okay inserting empty string"); } try { StringValidator.validateString((String)null, StringParameter.SYSTEM_ID); } catch (PDUStringException e) { fail("Should be okay inserting null string"); } try { StringValidator.validateString("smsgw", StringParameter.SYSTEM_ID); } catch (PDUStringException e) { fail("Should be okay inserting string that has length less than 16"); } try { StringValidator.validateString("smsgwsmsgwsmsgw", StringParameter.SYSTEM_ID); } catch (PDUStringException e) { fail("Should be okay inserting 15 char of string"); } try { StringValidator.validateString("smsgwsmsgwsmsgwe", StringParameter.SYSTEM_ID); fail("Should fail inserting 16 char of string"); } catch (PDUStringException e) { } try { StringValidator.validateString("smsgwsmsgwsmsgwee", StringParameter.SYSTEM_ID); fail("Should be fail inserting 16 char of string"); } catch (PDUStringException e) { } } } jsmpp-2.1.2/src/java/tests/org/jsmpp/extra/000077500000000000000000000000001246113105100205545ustar00rootroot00000000000000jsmpp-2.1.2/src/java/tests/org/jsmpp/extra/PendingResponseTest.java000066400000000000000000000072451246113105100253720ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.extra; import org.jsmpp.InvalidResponseException; import org.jsmpp.bean.Command; import static org.testng.Assert.*; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author uudashr * */ public class PendingResponseTest { private PendingResponse pendingResponse; @BeforeMethod public void setUp() throws Exception { pendingResponse = new PendingResponse(1000); } /** * Test {@link PendingResponse} for reached timeout. */ @Test(groups="checkintest") public void testReachTimeout() { try { notifyDone(1010, pendingResponse); pendingResponse.waitDone(); fail("Timeout should be reached"); } catch (ResponseTimeoutException e) { } catch (InvalidResponseException e) { fail("Timeout should be reached"); } } @Test(groups="checkintest") public void testUnreachTimeout() { try { notifyDone(90, pendingResponse); pendingResponse.waitDone(); } catch (ResponseTimeoutException e) { fail("Should be done with valid response"); } catch (InvalidResponseException e) { fail("Should be done with valid response"); } } @Test(groups="checkintest") public void testDoneWithInvalidResponse() { try { notifyInvalidResponse(90, pendingResponse); pendingResponse.waitDone(); System.out.println("DONE"); fail("Should throw InvalidResponseException"); } catch (ResponseTimeoutException e) { fail("Should throw InvalidResponseException"); } catch (InvalidResponseException e) { } } /** * Notify done of a pendingResponse on specified interval. * * @param timemillis is interval in millisecond. * @param pendingResponse is the pending response. */ private static void notifyDone(final long timemillis, final PendingResponse pendingResponse) { new Thread() { @Override public void run() { try { Thread.sleep(timemillis); pendingResponse.done(new Command()); } catch (InterruptedException e) { } } }.start(); } /** * Notify invalid response of a pendingResponse on specified interval. * * @param timemillis is interval in millisecond. * @param pendingResponse is the pending response. */ private static void notifyInvalidResponse(final long timemillis, final PendingResponse pendingResponse) { new Thread() { @Override public void run() { try { Thread.sleep(timemillis); pendingResponse.doneWithInvalidResponse( new InvalidResponseException("Invalid response message")); } catch (InterruptedException e) { } } }.start(); } } jsmpp-2.1.2/src/java/tests/org/jsmpp/extra/SessionStateTest.java000066400000000000000000000045421246113105100247100ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.extra; import static org.testng.Assert.*; import org.testng.annotations.Test; public class SessionStateTest { @Test(groups="checkintest") public void testClosedState() { SessionState sessionState = SessionState.CLOSED; assertFalse(sessionState.isReceivable()); assertFalse(sessionState.isTransmittable()); assertFalse(sessionState.isBound()); } @Test(groups="checkintest") public void testOpenState() { SessionState sessionState = SessionState.OPEN; assertFalse(sessionState.isReceivable()); assertFalse(sessionState.isTransmittable()); assertFalse(sessionState.isBound()); } @Test(groups="checkintest") public void testBoundTxState() { SessionState sessionState = SessionState.BOUND_TX; assertFalse(sessionState.isReceivable()); assertTrue(sessionState.isTransmittable()); assertTrue(sessionState.isBound()); } @Test(groups="checkintest") public void testBoundRxState() { SessionState sessionState = SessionState.BOUND_RX; assertTrue(sessionState.isReceivable()); assertFalse(sessionState.isTransmittable()); assertTrue(sessionState.isBound()); } @Test(groups="checkintest") public void testBoundTrxState() { SessionState sessionState = SessionState.BOUND_TRX; assertTrue(sessionState.isReceivable()); assertTrue(sessionState.isTransmittable()); assertTrue(sessionState.isBound()); } @Test(groups="checkintest") public void testUnbound() { SessionState sessionState = SessionState.UNBOUND; assertFalse(sessionState.isReceivable()); assertFalse(sessionState.isTransmittable()); assertFalse(sessionState.isBound()); } } jsmpp-2.1.2/src/java/tests/org/jsmpp/session/000077500000000000000000000000001246113105100211145ustar00rootroot00000000000000jsmpp-2.1.2/src/java/tests/org/jsmpp/session/BindRequestReceiverTest.java000066400000000000000000000072631246113105100265410ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.util.concurrent.TimeoutException; import org.jsmpp.bean.Bind; import org.jsmpp.bean.BindType; import static org.testng.Assert.*; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author uudashr * */ public class BindRequestReceiverTest { private BindRequestReceiver requestReceiver; @BeforeMethod public void setUp() { requestReceiver = new BindRequestReceiver(new DummyResponseHandler()); } @Test(groups="checkintest") public void testWaitTimeout() { try { BindRequest request = requestReceiver.waitForRequest(1000); fail("Should fail since no request for 1000 millis"); } catch (IllegalStateException e) { e.printStackTrace(); fail("Should not fail waitForRequest"); } catch (TimeoutException e) { } } @Test(groups="checkintest") public void testReceiveRequest() { try { requestReceiver.notifyAcceptBind(dummyBind()); BindRequest request = requestReceiver.waitForRequest(1000); } catch (IllegalStateException e) { fail("Should not fail waitForRequest and success accepting request"); } catch (TimeoutException e) { fail("Should not fail waitForRequest and success accepting request"); } try { requestReceiver.notifyAcceptBind(dummyBind()); fail("Should throw IllegalStateException"); } catch (IllegalStateException e) { } try { requestReceiver.waitForRequest(1000); fail("Should throw IllegalStateException"); } catch (IllegalStateException e) { } catch (TimeoutException e) { fail("Should throw IllegalStateException"); } } @Test(groups="checkintest") public void testNoSingleAccept() { try { requestReceiver.notifyAcceptBind(dummyBind()); } catch (IllegalStateException e) { fail("Should not fail waitForRequest and success accepting request"); } try { requestReceiver.notifyAcceptBind(dummyBind()); fail("Should throw IllegalStateException"); } catch (IllegalStateException e) { } } @Test(groups="checkintest") public void testNonSingleWait() { try { BindRequest request = requestReceiver.waitForRequest(1000); fail("Should throw TimeoutException"); } catch (IllegalStateException e) { fail("Should throw TimeoutException"); } catch (TimeoutException e) { } try { requestReceiver.waitForRequest(1000); fail("Should throw IllegalStateException"); } catch (IllegalStateException e) { } catch (TimeoutException e) { fail("Should throw IllegalStateException"); } } private static final Bind dummyBind() { Bind bind = new Bind(); bind.setCommandId(BindType.BIND_RX.commandId()); return bind; } } jsmpp-2.1.2/src/java/tests/org/jsmpp/session/BindRequestTest.java000066400000000000000000000100561246113105100250460ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import static org.testng.Assert.fail; import java.io.IOException; import org.jsmpp.PDUStringException; import org.jsmpp.bean.BindType; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author uudashr * */ public class BindRequestTest { private DummyResponseHandler responseHandler; private BindRequest bindRequest; @BeforeMethod public void setUp() { responseHandler = new DummyResponseHandler(); bindRequest = new BindRequest(1, BindType.BIND_TRX, null, null, null, null, null, null, responseHandler); } @Test(groups="checkintest") public void testSucceedAccept() { try { bindRequest.accept("sys"); } catch (PDUStringException e) { fail("Should succes accepting bind request"); } catch (IllegalStateException e1) { fail("Should succes accepting bind request"); } catch (IOException e1) { fail("Should succes accepting bind request"); } } @Test(groups="checkintest") public void testFailedAccept() { responseHandler.closeConnection(); try { bindRequest.accept("sys"); fail("Should throw IOException"); } catch (PDUStringException e) { fail("Should throw IOException"); } catch (IllegalStateException e) { fail("Should throw IOException"); } catch (IOException e) { } } @Test(groups="checkintest") public void testSucceedReject() { try { bindRequest.reject(-1); } catch (IllegalStateException e1) { fail("Should succes rejecting bind request"); } catch (IOException e1) { fail("Should succes rejecting bind request"); } } @Test(groups="checkintest") public void testFailedReject() { responseHandler.closeConnection(); try { bindRequest.reject(-1); fail("Should throw IOException"); } catch (IllegalStateException e) { fail("Should throw IOException"); } catch (IOException e) { } } @Test(groups="checkintest") public void testNonSingleAccept() { try { bindRequest.accept("sys"); } catch (PDUStringException e) { fail("Should success accepting bind request"); } catch (IllegalStateException e1) { fail("Should success accepting bind request"); } catch (IOException e1) { fail("Should success accepting bind request"); } try { bindRequest.accept("sys"); fail("Should fail on 2nd accept"); } catch (PDUStringException e) { fail("Should throw IllegalStateException"); } catch (IllegalStateException e) { } catch (IOException e) { fail("Should throw IllegalStateException"); } } @Test(groups="checkintest") public void testNonSingleReject() { try { bindRequest.reject(-1); } catch (IllegalStateException e1) { fail("Should success rejecting bind request"); } catch (IOException e1) { fail("Should success rejecting bind request"); } try { bindRequest.reject(-1); fail("Should fail on 2nd reject"); } catch (IllegalStateException e) { } catch (IOException e) { fail("Should throw IllegalStateException"); } } } jsmpp-2.1.2/src/java/tests/org/jsmpp/session/DummyResponseHandler.java000066400000000000000000000072461246113105100261000ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.bean.Bind; import org.jsmpp.bean.BindType; import org.jsmpp.bean.CancelSm; import org.jsmpp.bean.Command; import org.jsmpp.bean.DataSm; import org.jsmpp.bean.MessageState; import org.jsmpp.bean.QuerySm; import org.jsmpp.bean.ReplaceSm; import org.jsmpp.bean.SubmitMulti; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.SubmitSm; import org.jsmpp.extra.PendingResponse; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.util.MessageId; /** * @author uudashr * */ class DummyResponseHandler implements ServerResponseHandler { private boolean connectionClosed; public void notifyUnbonded() { } public PendingResponse removeSentItem(int sequenceNumber) { return null; } public void sendEnquireLinkResp(int sequenceNumber) throws IOException { } public void sendGenerickNack(int commandStatus, int sequenceNumber) throws IOException { } public void sendNegativeResponse(int originalCommandId, int commandStatus, int sequenceNumber) throws IOException { if (connectionClosed) { throw new IOException("Connection closed"); } } public void sendUnbindResp(int sequenceNumber) throws IOException { } public void processBind(Bind bind) { } public QuerySmResult processQuerySm(QuerySm querySm) throws ProcessRequestException { return null; } public SubmitMultiResult processSubmitMulti(SubmitMulti submitMulti) throws ProcessRequestException { return null; } public void sendSubmitMultiResponse(SubmitMultiResult submiitMultiResult, int sequenceNumber) throws IOException { } public MessageId processSubmitSm(SubmitSm submitSm) throws ProcessRequestException { return null; } public void sendBindResp(String systemId, BindType bindType, int sequenceNumber) throws IOException { if (connectionClosed) { throw new IOException("Connection closed"); } } public void sendSubmitSmResponse(MessageId messageId, int sequenceNumber) throws IOException { } public DataSmResult processDataSm(DataSm dataSm) throws ProcessRequestException { return null; } public void sendDataSmResp(DataSmResult dataSmResult, int sequenceNumber) throws IOException { } public void processCancelSm(CancelSm cancelSm) throws ProcessRequestException { } public void sendCancelSmResp(int sequenceNumber) throws IOException { } public void sendQuerySmResp(String messageId, String finalDate, MessageState messageState, byte errorCode, int sequenceNumber) throws IOException { } public void processReplaceSm(ReplaceSm replaceSm) throws ProcessRequestException { } public void sendReplaceSmResp(int sequenceNumber) throws IOException { } public void closeConnection() { connectionClosed = true; } }jsmpp-2.1.2/src/java/tests/org/jsmpp/util/000077500000000000000000000000001246113105100204065ustar00rootroot00000000000000jsmpp-2.1.2/src/java/tests/org/jsmpp/util/COctetStringNullOrFixedLengthTest.java000066400000000000000000000034201246113105100277360ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import static org.testng.Assert.*; import org.testng.annotations.Test; /** * @author uudashr * */ public class COctetStringNullOrFixedLengthTest { @Test(groups="checkintest") public void testNull() throws Exception { assertTrue(StringValidator.isCOctetStringNullOrNValValid((String)null, 10)); } @Test(groups="checkintest") public void testEmpty() throws Exception { assertTrue(StringValidator.isCOctetStringNullOrNValValid("", 10)); } @Test(groups="checkintest") public void testSingleChar() throws Exception { assertFalse(StringValidator.isCOctetStringNullOrNValValid("1", 10)); } @Test(groups="checkintest") public void testFixedLength() throws Exception { assertTrue(StringValidator.isCOctetStringNullOrNValValid("123456789", 10)); } @Test(groups="checkintest") public void testNonExceedLength() throws Exception { assertFalse(StringValidator.isCOctetStringNullOrNValValid("01234567", 10)); } @Test(groups="checkintest") public void testExceedLength() throws Exception { assertFalse(StringValidator.isCOctetStringNullOrNValValid("01234567891", 10)); } } jsmpp-2.1.2/src/java/tests/org/jsmpp/util/ComposerDecomposerReaderTest.java000066400000000000000000000072501246113105100270500ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import static org.testng.Assert.*; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.BindResp; import org.jsmpp.bean.BindType; import org.testng.annotations.Test; /** * Test composing PDU, decompose and read. * @author uudashr * */ public class ComposerDecomposerReaderTest { private static final boolean DEBUG = false; @Test(groups="checkintest") public void lowLevel() { byte[] b = null; String systemId = "smsc"; PDUByteBuffer buf = new PDUByteBuffer(BindType.BIND_TRX.responseCommandId(), 0, 1); buf.append(systemId); b = buf.toBytes(); assertEquals(b.length, 16 + systemId.length() + 1); printLog("Length of bytes : " + b.length); SequentialBytesReader reader = new SequentialBytesReader(b); assertEquals(b.length, reader.remainBytesLength()); int commandLength = reader.readInt(); assertEquals(commandLength, b.length); assertEquals(4, reader.cursor); assertEquals(b.length - 4, reader.remainBytesLength()); int commandId = reader.readInt(); assertEquals(commandId, BindType.BIND_TRX.responseCommandId()); assertEquals(8, reader.cursor); assertEquals(b.length - 8, reader.remainBytesLength()); int commandStatus = reader.readInt(); assertEquals(commandStatus, SMPPConstant.STAT_ESME_ROK); assertEquals(12, reader.cursor); assertEquals(b.length - 12, reader.remainBytesLength()); int sequenceNumber = reader.readInt(); assertEquals(sequenceNumber, 1); assertEquals(16, reader.cursor); assertEquals(b.length - 16, reader.remainBytesLength()); String readedSystemId = reader.readCString(); assertEquals(readedSystemId, systemId); } @Test(groups="checkintest") public void highLevel() { PDUComposer composer = new DefaultComposer(); PDUDecomposer decomposer = new DefaultDecomposer(); byte[] b = null; String systemId = "smsc"; BindType bindType = BindType.BIND_TRX; try { b = composer.bindResp(bindType.responseCommandId(), 1, systemId); assertEquals(b.length, 16 + systemId.length() + 1); printLog("Length of bytes : " + b.length); } catch (PDUStringException e) { fail("Failed composing bind response", e); } try { BindResp resp = decomposer.bindResp(b); assertEquals(resp.getCommandLength(), b.length); assertEquals(resp.getCommandId(), bindType.responseCommandId()); assertEquals(resp.getCommandStatus(), SMPPConstant.STAT_ESME_ROK); assertEquals(resp.getSequenceNumber(), 1); assertEquals(resp.getSystemId(), systemId); } catch (PDUStringException e) { fail("Failed decomposing bind response", e); } } private static void printLog(String message) { if (DEBUG) { System.out.println(message); } } } jsmpp-2.1.2/src/java/tests/org/jsmpp/util/DateFormatterTest.java000066400000000000000000000050001246113105100246450ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import java.util.Calendar; import java.util.Date; import static org.testng.Assert.*; import org.testng.annotations.Test; /** * @author uudashr * */ public class DateFormatterTest { @Test(groups="checkintest") public void testStaticAbsoluteFormatter() { String formatted = AbsoluteTimeFormatter.format(07, 12, 26, 11, 37, 03, 8, 45, '+'); assertEquals(formatted, "071226113703845+"); } @Test(groups="checkintest") public void testStaticRelativeFormatter() { String formatted = RelativeTimeFormatter.format(07, 12, 26, 12, 46, 10); assertEquals(formatted, "071226124610000R"); } @Test(groups="checkintest") public void formatNullDate() { TimeFormatter timeFormatter = new AbsoluteTimeFormatter(); assertNull(timeFormatter.format((Date)null)); assertNull(timeFormatter.format((Calendar)null)); timeFormatter = new RelativeTimeFormatter(); assertNull(timeFormatter.format((Date)null)); assertNull(timeFormatter.format((Calendar)null)); } @Test(groups="checkintest") public void validateAbsoluteDate() throws Exception { String formatted = AbsoluteTimeFormatter.format(07, 12, 26, 11, 37, 03, 8, 45, '+'); StringValidator.validateString(formatted, StringParameter.SCHEDULE_DELIVERY_TIME); StringValidator.validateString(formatted, StringParameter.VALIDITY_PERIOD); StringValidator.validateString(formatted, StringParameter.FINAL_DATE); } @Test(groups="checkintest") public void validateRelativeDate() throws Exception { String formatted = RelativeTimeFormatter.format(07, 12, 26, 12, 46, 10); StringValidator.validateString(formatted, StringParameter.SCHEDULE_DELIVERY_TIME); StringValidator.validateString(formatted, StringParameter.VALIDITY_PERIOD); StringValidator.validateString(formatted, StringParameter.FINAL_DATE); } } jsmpp-2.1.2/src/java/tests/org/jsmpp/util/DeliveryReceiptParserTest.java000066400000000000000000000063741246113105100263770ustar00rootroot00000000000000package org.jsmpp.util; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; import java.util.Calendar; import java.util.Date; import org.jsmpp.bean.DeliveryReceipt; import org.testng.annotations.Test; /** * @author uudashr * */ public class DeliveryReceiptParserTest { private PDUDecomposer decomposer = new DefaultDecomposer(); private static final String ORIGINAL_MESSAGE = "testing jsmpp bow"; @Test public void parseTextWithLowerCase() { try { DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:0809011130 done date:0809011131 stat:DELIVRD err:000 text:" + ORIGINAL_MESSAGE); assertEquals(delReceipt.getText(), ORIGINAL_MESSAGE); Date submitDate = delReceipt.getSubmitDate(); Date expectedSubmitDate = createDate(2008, 9, 1, 11, 30); assertEquals(submitDate, expectedSubmitDate); Date doneDate = delReceipt.getDoneDate(); Date expectedDoneDate = createDate(2008, 9, 1, 11, 31); assertEquals(doneDate, expectedDoneDate); } catch (InvalidDeliveryReceiptException e) { fail("Failed parsing delivery receipt:" + e.getMessage()); } } @Test public void parsingTextWithUpperCase() { try { DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:0809011130 done date:0809011131 stat:DELIVRD err:000 Text:" + ORIGINAL_MESSAGE); assertEquals(delReceipt.getText(), ORIGINAL_MESSAGE); Date submitDate = delReceipt.getSubmitDate(); Date expectedSubmitDate = createDate(2008, 9, 1, 11, 30); assertEquals(submitDate, expectedSubmitDate); Date doneDate = delReceipt.getDoneDate(); Date expectedDoneDate = createDate(2008, 9, 1, 11, 31); assertEquals(doneDate, expectedDoneDate); } catch (InvalidDeliveryReceiptException e) { fail("Failed parsing delivery receipt:" + e.getMessage()); } } @Test public void parseWithNoTextAttribute() { try { DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:0809011130 done date:0809011131 stat:DELIVRD err:000 " + ORIGINAL_MESSAGE); assertEquals(delReceipt.getText(), null); Date submitDate = delReceipt.getSubmitDate(); Date expectedSubmitDate = createDate(2008, 9, 1, 11, 30); assertEquals(submitDate, expectedSubmitDate); Date doneDate = delReceipt.getDoneDate(); Date expectedDoneDate = createDate(2008, 9, 1, 11, 31); assertEquals(doneDate, expectedDoneDate); } catch (InvalidDeliveryReceiptException e) { e.printStackTrace(); fail("Failed parsing delivery receipt:" + e.getMessage()); } } private static Date createDate(int year, int month, int day, int hour, int minute) { Calendar cal = Calendar.getInstance(); cal.set(year, month - 1, day, hour, minute, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } } jsmpp-2.1.2/src/java/tests/org/jsmpp/util/MessageIdValidationTest.java000066400000000000000000000013321246113105100257640ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * @author uudashr * */ public class MessageIdValidationTest { // TODO uudashr: create test case for message_id validation } jsmpp-2.1.2/src/java/tests/org/jsmpp/util/OctetStringValidationTest.java000066400000000000000000000045321246113105100263750ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import org.jsmpp.PDUStringException; import org.testng.annotations.Test; /** * @author uudashr * */ public class OctetStringValidationTest { private static final String FULL_LENGTH_TEXT = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor"; private static final int MAX_SHORT_MESSAGE_LENGTH = 254; @Test public void zeroLength() throws Exception { String shortMessage = ""; assertEquals(shortMessage.length(), 0); StringValidator.validateString(shortMessage.getBytes(), StringParameter.SHORT_MESSAGE); } @Test public void nonZeroBelow255Length() throws Exception { String shortMessage = "This is a simple message"; assertTrue(shortMessage.length() > 0); assertTrue(shortMessage.length() <= MAX_SHORT_MESSAGE_LENGTH); StringValidator.validateString(shortMessage.getBytes(), StringParameter.SHORT_MESSAGE); } @Test public void fullLegth() throws Exception { assertEquals(FULL_LENGTH_TEXT.length(), MAX_SHORT_MESSAGE_LENGTH); StringValidator.validateString(FULL_LENGTH_TEXT.getBytes(), StringParameter.SHORT_MESSAGE); } @Test(expectedExceptions = PDUStringException.class) public void overLengthText() throws Exception { String shortMessage = FULL_LENGTH_TEXT + " "; assertTrue(shortMessage.length() > MAX_SHORT_MESSAGE_LENGTH); StringValidator.validateString(shortMessage.getBytes(), StringParameter.SHORT_MESSAGE); } } jsmpp-2.1.2/src/java/tests/org/jsmpp/util/OctetUtilTest.java000066400000000000000000000045241246113105100240320ustar00rootroot00000000000000package org.jsmpp.util; import static org.testng.Assert.assertEquals; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import org.testng.annotations.Test; /** * @author uudashr * */ public class OctetUtilTest { /** * Test the int2bytes and bytes2int conversion. */ @Test public void intConversion() { int in = Integer.MIN_VALUE; byte[] bytes = OctetUtil.intToBytes(in); assertEquals(bytes.length, 4); int out = OctetUtil.bytesToInt(bytes); assertEquals(out, in); } /** * Test the short2bytes and bytes2short conversion. */ @Test public void shortConversion() { short in = Short.MIN_VALUE; byte[] bytes = OctetUtil.shortToBytes(in); assertEquals(bytes.length, 2); short out = OctetUtil.bytesToShort(bytes); assertEquals(out, in); } /** * Test another short2bytes and bytes2short conversion. */ @Test public void testAnotherShortConversion() { byte[] bytes = new byte[] {-10, 10}; short shortVal = OctetUtil.bytesToShort(bytes); byte[] anotherByte = OctetUtil.shortToBytes(shortVal); assertEquals(anotherByte, bytes); short anotherShortVal = OctetUtil.bytesToShort(anotherByte); assertEquals(anotherShortVal, shortVal); } /** * This is test from igor.skornyakov */ @Test public void testShortEncodeFromIgor() { assertEquals(0x1D4, OctetUtil.bytesToShort(new byte[] {1, (byte)0xD4}, 0)); } /** * Short encoded test from igor.skornyakov */ @Test public void testShortEncode() { short val = (short)0x1d4; byte[] bytes = OctetUtil.shortToBytes((short)0x1d4); short anotherVal = OctetUtil.bytesToShort(bytes); assertEquals(val, anotherVal); } } jsmpp-2.1.2/src/java/tests/org/jsmpp/util/PDUByteBufferTest.java000066400000000000000000000073621246113105100245270ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import static org.testng.Assert.assertEquals; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author uudashr * */ public class PDUByteBufferTest { private static final int BYTE_LENGTH = 1; private static final int INTEGER_LENGTH = 4; private static final int INITIAL_LENGTH = INTEGER_LENGTH; private PDUByteBuffer byteBuffer; @BeforeMethod public void setUp() { byteBuffer = new PDUByteBuffer(new SimpleCapacityPolicy()); } @Test(groups="checkintest") public void initialLengthValidity() { byte[] pdu = byteBuffer.toBytes(); assertEquals(pdu.length, INITIAL_LENGTH); assertEquals(pdu.length, byteBuffer.getCommandLengthValue()); assertEquals(pdu.length, byteBuffer.getBytesLength()); } @Test(groups="checkintest", dependsOnMethods="initialLengthValidity") public void testLengthValidityForIntAppends() { for (int i = 0; i < 5; i++) { byteBuffer.append(10); byte[] pdu = byteBuffer.toBytes(); assertEquals(pdu.length, INITIAL_LENGTH + (INTEGER_LENGTH * (i + 1)), "Failed on iteration " + i); assertEquals(pdu.length, byteBuffer.getCommandLengthValue()); assertEquals(pdu.length, byteBuffer.getBytesLength()); } } @Test(groups="checkintest", dependsOnMethods="initialLengthValidity") public void testLengthValidityForByteAppends() { for (int i = 0; i < 5; i++) { byteBuffer.append((byte)10); byte[] pdu = byteBuffer.toBytes(); assertEquals(pdu.length, INITIAL_LENGTH + (BYTE_LENGTH * (i + 1)), "Failed on iteration " + i); assertEquals(pdu.length, byteBuffer.getCommandLengthValue(), "Failed on iteration " + i); assertEquals(pdu.length, byteBuffer.getBytesLength(), "Failed on iteration " + i); } } @Test(groups="checkintest", dependsOnMethods="initialLengthValidity") public void testLengthValidityForCString() { String hello = "PDUByteBuffer integration test for JSMPP API"; for (int i = 0; i < 5; i++) { byteBuffer.append(hello); byte[] pdu = byteBuffer.toBytes(); assertEquals(pdu.length, INITIAL_LENGTH + (hello.length() * (i + 1)) + (i + 1), "Failed on iteration " + i); assertEquals(pdu.length, byteBuffer.getCommandLengthValue(), "Failed on iteration " + i); assertEquals(pdu.length, byteBuffer.getBytesLength(), "Failed on iteration " + i); } } @Test(groups="checkintest", dependsOnMethods="initialLengthValidity") public void testLengthValidityForString() { String hello = "PDUByteBuffer integration test for JSMPP API"; for (int i = 0; i < 5; i++) { byteBuffer.append(hello, false); byte[] pdu = byteBuffer.toBytes(); assertEquals(pdu.length, INITIAL_LENGTH + (hello.length() * (i + 1)), "Failed on iteration " + i); assertEquals(pdu.length, byteBuffer.getCommandLengthValue(), "Failed on iteration " + i); assertEquals(pdu.length, byteBuffer.getBytesLength(), "Failed on iteration " + i); } } } jsmpp-2.1.2/src/java/tests/org/jsmpp/util/SequenceTest.java000066400000000000000000000024621246113105100236650ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import static org.testng.Assert.*; import org.testng.annotations.Test; /** * @author uudashr * */ public class SequenceTest { @Test(groups="checkintest") public void testSequence() { Sequence sequence = new Sequence(1); for (int i = 1; i < 100; i++) { assertEquals(sequence.nextValue(), i); } } @Test(groups="checkintest") public void testCycle() { Sequence sequence = new Sequence(Integer.MAX_VALUE - 2); assertEquals(sequence.nextValue(), Integer.MAX_VALUE - 2); assertEquals(sequence.nextValue(), Integer.MAX_VALUE - 1); assertEquals(sequence.nextValue(), Integer.MAX_VALUE); assertEquals(sequence.nextValue(), 1); } } jsmpp-2.1.2/src/java/tests/org/jsmpp/util/SequentialByteReaderTest.java000066400000000000000000000024771246113105100262040ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import static org.testng.Assert.*; import org.testng.annotations.Test; /** * Test the {@link SequentialBytesReader}. * * @author uudashr * */ public class SequentialByteReaderTest { /** * Test reading byte until null (0). */ @Test public void testReadUntilNull() { byte[] bytes = "Hello".getBytes(); byte[] nullDelimitedBytes = new byte[bytes.length + 1]; System.arraycopy(bytes, 0, nullDelimitedBytes, 0, bytes.length); assertEquals(nullDelimitedBytes[bytes.length], (byte)0); SequentialBytesReader reader = new SequentialBytesReader(nullDelimitedBytes); byte[] readedBytes = reader.readBytesUntilNull(); assertEquals(readedBytes, bytes); } } jsmpp-2.1.2/src/java/tests/org/jsmpp/util/ShortMessageValidation.java000066400000000000000000000013271246113105100256730ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * @author uudashr * */ public class ShortMessageValidation { // TODO uudashr: create test case short message validation } jsmpp-2.1.2/src/java/tests/org/jsmpp/util/StringValidatorChekNullOrFixedLengthTest.java000066400000000000000000000034261246113105100313030ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import static org.testng.Assert.*; import org.testng.annotations.Test; /** * @author uudashr * */ public class StringValidatorChekNullOrFixedLengthTest { @Test(groups="checkintest") public void testNull() throws Exception { assertTrue(StringValidator.isCOctetStringNullOrNValValid((String)null, 10)); } @Test(groups="checkintest") public void testEmpty() throws Exception { assertTrue(StringValidator.isCOctetStringNullOrNValValid("", 10)); } @Test(groups="checkintest") public void testSingleChar() throws Exception { assertFalse(StringValidator.isCOctetStringNullOrNValValid("1", 10)); } @Test(groups="checkintest") public void testFixedLength() throws Exception { assertTrue(StringValidator.isCOctetStringNullOrNValValid("123456789", 10)); } @Test(groups="checkintest") public void testNonExceedLength() throws Exception { assertFalse(StringValidator.isCOctetStringNullOrNValValid("01234567", 10)); } @Test(groups="checkintest") public void testExceedLength() throws Exception { assertFalse(StringValidator.isCOctetStringNullOrNValValid("01234567891", 10)); } } jsmpp-2.1.2/src/main/000077500000000000000000000000001246113105100143525ustar00rootroot00000000000000jsmpp-2.1.2/src/main/java/000077500000000000000000000000001246113105100152735ustar00rootroot00000000000000jsmpp-2.1.2/src/main/java/org/000077500000000000000000000000001246113105100160625ustar00rootroot00000000000000jsmpp-2.1.2/src/main/java/org/jsmpp/000077500000000000000000000000001246113105100172135ustar00rootroot00000000000000jsmpp-2.1.2/src/main/java/org/jsmpp/DefaultPDUReader.java000066400000000000000000000062561246113105100231470ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import org.jsmpp.bean.Command; import org.jsmpp.util.OctetUtil; /** * Default implementation of {@link PDUReader}. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class DefaultPDUReader implements PDUReader { /* (non-Javadoc) * @see org.jsmpp.PDUReader#readPDUHeader(java.io.DataInputStream) */ public Command readPDUHeader(DataInputStream in) throws InvalidCommandLengthException, IOException { Command header = new Command(); header.setCommandLength(in.readInt()); if (header.getCommandLength() < 16) { // command length to short, read the left dump anyway byte[] dump = new byte[header.getCommandLength()]; in.read(dump, 4, header.getCommandLength() - 4); throw new InvalidCommandLengthException("Command length " + header.getCommandLength() + " is to short"); } header.setCommandId(in.readInt()); header.setCommandStatus(in.readInt()); header.setSequenceNumber(in.readInt()); return header; } /* (non-Javadoc) * @see org.jsmpp.PDUReader#readPDU(java.io.InputStream, org.jsmpp.bean.Command) */ public byte[] readPDU(InputStream in, Command pduHeader) throws IOException { return readPDU(in, pduHeader.getCommandLength(), pduHeader .getCommandId(), pduHeader.getCommandStatus(), pduHeader .getSequenceNumber()); } /* (non-Javadoc) * @see org.jsmpp.PDUReader#readPDU(java.io.InputStream, int, int, int, int) */ public byte[] readPDU(InputStream in, int commandLength, int commandId, int commandStatus, int sequenceNumber) throws IOException { byte[] b = new byte[commandLength]; System.arraycopy(OctetUtil.intToBytes(commandLength), 0, b, 0, 4); System.arraycopy(OctetUtil.intToBytes(commandId), 0, b, 4, 4); System.arraycopy(OctetUtil.intToBytes(commandStatus), 0, b, 8, 4); System.arraycopy(OctetUtil.intToBytes(sequenceNumber), 0, b, 12, 4); if (commandLength > 16) { int len = commandLength - 16; int totalReaded = -1; synchronized (in) { totalReaded = in.read(b, 16, commandLength - 16); } if (totalReaded != len) { throw new IOException( "Unexpected length of byte readed. Expecting " + len + " but only read " + totalReaded); } } return b; } } jsmpp-2.1.2/src/main/java/org/jsmpp/DefaultPDUSender.java000066400000000000000000000402511246113105100231560ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.bean.BindType; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.DestinationAddress; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.InterfaceVersion; import org.jsmpp.bean.MessageState; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.ReplaceIfPresentFlag; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.bean.UnsuccessDelivery; import org.jsmpp.util.DefaultComposer; import org.jsmpp.util.PDUComposer; /** * The SMPP PDU reader class. * * @author uudashr * @version 1.1 * @since 1.0 * */ public class DefaultPDUSender implements PDUSender { private final PDUComposer pduComposer; /** * Default constructor. */ public DefaultPDUSender() { this(new DefaultComposer()); } /** * Construct with specified PDU composer. * * @param pduComposer is the PDU composer. */ public DefaultPDUSender(PDUComposer pduComposer) { this.pduComposer = pduComposer; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendHeader(java.io.OutputStream, int, int, int) */ public byte[] sendHeader(OutputStream os, int commandId, int commandStatus, int sequenceNumber) throws IOException { byte[] b = pduComposer.composeHeader(commandId, commandStatus, sequenceNumber); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendBind(java.io.OutputStream, * org.jsmpp.BindType, int, java.lang.String, java.lang.String, * java.lang.String, org.jsmpp.InterfaceVersion, * org.jsmpp.TypeOfNumber, org.jsmpp.NumberingPlanIndicator, * java.lang.String) */ public byte[] sendBind(OutputStream os, BindType bindType, int sequenceNumber, String systemId, String password, String systemType, InterfaceVersion interfaceVersion, TypeOfNumber addrTon, NumberingPlanIndicator addrNpi, String addressRange) throws PDUStringException, IOException { byte[] b = pduComposer.bind(bindType.commandId(), sequenceNumber, systemId, password, systemType, interfaceVersion.value(), addrTon.value(), addrNpi.value(), addressRange); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendBindResp(java.io.OutputStream, int, int, * java.lang.String) */ public byte[] sendBindResp(OutputStream os, int commandId, int sequenceNumber, String systemId) throws PDUStringException, IOException { byte[] b = pduComposer.bindResp(commandId, sequenceNumber, systemId); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendUnbind(java.io.OutputStream, int) */ public byte[] sendUnbind(OutputStream os, int sequenceNumber) throws IOException { byte[] b = pduComposer.unbind(sequenceNumber); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendGenericNack(java.io.OutputStream, int, int) */ public byte[] sendGenericNack(OutputStream os, int commandStatus, int sequenceNumber) throws IOException { byte[] b = pduComposer.genericNack(commandStatus, sequenceNumber); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendUnbindResp(java.io.OutputStream, int, int) */ public byte[] sendUnbindResp(OutputStream os, int commandStatus, int sequenceNumber) throws IOException { byte[] b = pduComposer.unbindResp(commandStatus, sequenceNumber); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendEnquireLink(java.io.OutputStream, int) */ public byte[] sendEnquireLink(OutputStream os, int sequenceNumber) throws IOException { byte[] b = pduComposer.enquireLink(sequenceNumber); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendEnquireLinkResp(java.io.OutputStream, int) */ public byte[] sendEnquireLinkResp(OutputStream os, int sequenceNumber) throws IOException { byte[] b = pduComposer.enquireLinkResp(sequenceNumber); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendSubmitSm(java.io.OutputStream, int, * java.lang.String, org.jsmpp.TypeOfNumber, * org.jsmpp.NumberingPlanIndicator, java.lang.String, * org.jsmpp.TypeOfNumber, org.jsmpp.NumberingPlanIndicator, * java.lang.String, org.jsmpp.bean.ESMClass, byte, byte, * java.lang.String, java.lang.String, * org.jsmpp.bean.RegisteredDelivery, byte, org.jsmpp.bean.DataCoding, * byte, byte[], org.jsmpp.bean.OptionalParameter[]) */ public byte[] sendSubmitSm(OutputStream os, int sequenceNumber, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocoId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte replaceIfPresent, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException, IOException { byte[] b = pduComposer.submitSm(sequenceNumber, serviceType, sourceAddrTon.value(), sourceAddrNpi.value(), sourceAddr, destAddrTon.value(), destAddrNpi.value(), destinationAddr, esmClass.value(), protocoId, priorityFlag, scheduleDeliveryTime, validityPeriod, registeredDelivery .value(), replaceIfPresent, dataCoding.value(), smDefaultMsgId, shortMessage, optionalParameters); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendSubmitSmResp(java.io.OutputStream, int, * java.lang.String) */ public byte[] sendSubmitSmResp(OutputStream os, int sequenceNumber, String messageId) throws PDUStringException, IOException { byte[] b = pduComposer.submitSmResp(sequenceNumber, messageId); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendQuerySm(java.io.OutputStream, int, * java.lang.String, org.jsmpp.TypeOfNumber, * org.jsmpp.NumberingPlanIndicator, java.lang.String) */ public byte[] sendQuerySm(OutputStream os, int sequenceNumber, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr) throws PDUStringException, IOException { byte[] b = pduComposer.querySm(sequenceNumber, messageId, sourceAddrTon .value(), sourceAddrNpi.value(), sourceAddr); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendQuerySmResp(java.io.OutputStream, int, * java.lang.String, java.lang.String, org.jsmpp.bean.MessageState, * byte) */ public byte[] sendQuerySmResp(OutputStream os, int sequenceNumber, String messageId, String finalDate, MessageState messageState, byte errorCode) throws PDUStringException, IOException { byte[] b = pduComposer.querySmResp(sequenceNumber, messageId, finalDate, messageState.value(), errorCode); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendDeliverSm(java.io.OutputStream, int, * java.lang.String, org.jsmpp.TypeOfNumber, * org.jsmpp.NumberingPlanIndicator, java.lang.String, * org.jsmpp.TypeOfNumber, org.jsmpp.NumberingPlanIndicator, * java.lang.String, org.jsmpp.bean.ESMClass, byte, byte, * org.jsmpp.bean.RegisteredDelivery, org.jsmpp.bean.DataCoding, * byte[], org.jsmpp.bean.OptionalParameter[]) */ public byte[] sendDeliverSm(OutputStream os, int sequenceNumber, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocoId, byte priorityFlag, RegisteredDelivery registeredDelivery, DataCoding dataCoding, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException, IOException { byte[] b = pduComposer.deliverSm(sequenceNumber, serviceType, sourceAddrTon.value(), sourceAddrNpi.value(), sourceAddr, destAddrTon.value(), destAddrNpi.value(), destinationAddr, esmClass.value(), protocoId, priorityFlag, registeredDelivery .value(), dataCoding.value(), shortMessage, optionalParameters); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendDeliverSmResp(java.io.OutputStream, int) */ public byte[] sendDeliverSmResp(OutputStream os, int sequenceNumber) throws IOException { byte[] b = pduComposer.deliverSmResp(sequenceNumber); writeAndFlush(os, b); return b; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendDataSm(java.io.OutputStream, int, * java.lang.String, org.jsmpp.TypeOfNumber, * org.jsmpp.NumberingPlanIndicator, java.lang.String, * org.jsmpp.TypeOfNumber, org.jsmpp.NumberingPlanIndicator, * java.lang.String, org.jsmpp.bean.ESMClass, * org.jsmpp.bean.RegisteredDelivery, org.jsmpp.bean.DataCoding, * org.jsmpp.bean.OptionalParameter[]) */ public byte[] sendDataSm(OutputStream os, int sequenceNumber, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, RegisteredDelivery registeredDelivery, DataCoding dataCoding, OptionalParameter... optionalParameters) throws PDUStringException, IOException { byte[] b = pduComposer.dataSm(sequenceNumber, serviceType, sourceAddrTon.value(), sourceAddrNpi.value(), sourceAddr, destAddrTon.value(), destAddrNpi.value(), destinationAddr, esmClass.value(), registeredDelivery.value(), dataCoding .value(), optionalParameters); writeAndFlush(os, b); return b; } public byte[] sendDataSmResp(OutputStream os, int sequenceNumber, String messageId, OptionalParameter... optionalParameters) throws PDUStringException, IOException { byte[] b = pduComposer.dataSmResp(sequenceNumber, messageId, optionalParameters); writeAndFlush(os, b); return b; } public byte[] sendCancelSm(OutputStream os, int sequenceNumber, String serviceType, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr) throws PDUStringException, IOException { byte[] b = pduComposer.cancelSm(sequenceNumber, serviceType, messageId, sourceAddrTon.value(), sourceAddrNpi.value(), sourceAddr, destAddrTon.value(), destAddrNpi.value(), destinationAddr); writeAndFlush(os, b); return b; } public byte[] sendCancelSmResp(OutputStream os, int sequenceNumber) throws IOException { byte[] b = pduComposer.cancelSmResp(sequenceNumber); writeAndFlush(os, b); return b; } public byte[] sendReplaceSm(OutputStream os, int sequenceNumber, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte smDefaultMsgId, byte[] shortMessage) throws PDUStringException, IOException { byte[] b = pduComposer.replaceSm(sequenceNumber, messageId, sourceAddrTon.value(), sourceAddrNpi.value(), sourceAddr, scheduleDeliveryTime, validityPeriod, registeredDelivery .value(), smDefaultMsgId, shortMessage); writeAndFlush(os, b); return b; } public byte[] sendReplaceSmResp(OutputStream os, int sequenceNumber) throws IOException { byte[] b = pduComposer.replaceSmResp(sequenceNumber); writeAndFlush(os, b); return b; } public byte[] sendSubmiMulti(OutputStream os, int sequenceNumber, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, DestinationAddress[] destinationAddresses, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, ReplaceIfPresentFlag replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException, InvalidNumberOfDestinationsException, IOException { byte[] b = pduComposer.submitMulti(sequenceNumber, serviceType, sourceAddrTon.value(), sourceAddrNpi.value(), sourceAddr, destinationAddresses, esmClass.value(), protocolId, priorityFlag, scheduleDeliveryTime, validityPeriod, registeredDelivery.value(), replaceIfPresentFlag.value(), dataCoding.value(), smDefaultMsgId, shortMessage, optionalParameters); writeAndFlush(os, b); return b; } public byte[] sendSubmitMultiResp(OutputStream os, int sequenceNumber, String messageId, UnsuccessDelivery... unsuccessDeliveries) throws PDUStringException, IOException { byte[] b = pduComposer.submitMultiResp(sequenceNumber, messageId, unsuccessDeliveries); writeAndFlush(os, b); return b; } public byte[] sendAlertNotification(OutputStream os, int sequenceNumber, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte esmeAddrTon, byte esmeAddrNpi, String esmeAddr, OptionalParameter... optionalParameters) throws PDUStringException, IOException { byte[] b = pduComposer.alertNotification(sequenceNumber, sourceAddrTon, sourceAddrNpi, sourceAddr, esmeAddrTon, esmeAddrNpi, esmeAddr, optionalParameters); writeAndFlush(os, b); return b; } private static void writeAndFlush(OutputStream out, byte[] b) throws IOException { out.write(b); out.flush(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/GenericNackResponseException.java000066400000000000000000000020201246113105100256170ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; /** * @author uudashr * */ public class GenericNackResponseException extends InvalidResponseException { private static final long serialVersionUID = -5938563802952633189L; private final int commandStatus; public GenericNackResponseException(String message, int commandStatus) { super(message); this.commandStatus = commandStatus; } public int getCommandStatus() { return commandStatus; } } jsmpp-2.1.2/src/main/java/org/jsmpp/InvalidCommandLengthException.java000066400000000000000000000031601246113105100257640ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; /** * This exception is thrown if command_length of PDU is not acceptable. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class InvalidCommandLengthException extends PDUException { private static final long serialVersionUID = -3097470067910064841L; /** * Default constructor. */ public InvalidCommandLengthException() { super(); } /** * Construct with specified message and cause. * * @param message is the detail message. * @param cause is the parent cause. */ public InvalidCommandLengthException(String message, Throwable cause) { super(message, cause); } /** * Construct with specified message. * * @param message is the detail message. */ public InvalidCommandLengthException(String message) { super(message); } /** * Construct with specified cause. * * @param cause is the parent cause. */ public InvalidCommandLengthException(Throwable cause) { super(cause); } } jsmpp-2.1.2/src/main/java/org/jsmpp/InvalidNumberOfDestinationsException.java000066400000000000000000000013231246113105100273450ustar00rootroot00000000000000package org.jsmpp; /** * This exception should be thrown if there is an invalid number of destination * address used by submit_multi. * * @author uudashr * */ public class InvalidNumberOfDestinationsException extends PDUException { private static final long serialVersionUID = -1515128166927438310L; private int actualLength; /** * Default constructor. * * @param message is the message. * @param actualLength the actual length. */ public InvalidNumberOfDestinationsException(String message, int actualLength) { super(message); this.actualLength = actualLength; } public int getActualLength() { return actualLength; } } jsmpp-2.1.2/src/main/java/org/jsmpp/InvalidRequestException.java000066400000000000000000000027521246113105100247020ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; /** * This exception is thrown when receive unexpected request. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class InvalidRequestException extends Exception { private static final long serialVersionUID = -2275241874120654607L; /** * Default constructor. */ public InvalidRequestException() { super(); } /** * Construct with specified message and cause. * * @param message is the detail message. * @param cause is the parent cause. */ public InvalidRequestException(String message, Throwable cause) { super(message, cause); } /** * Construct with specified message. * * @param message is the detail message. */ public InvalidRequestException(String message) { super(message); } /** * Construct with specified cause. * * @param cause is the parent cause. */ public InvalidRequestException(Throwable cause) { super(cause); } } jsmpp-2.1.2/src/main/java/org/jsmpp/InvalidResponseException.java000066400000000000000000000024301246113105100250410ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; /** * This exception thrown if we receive unexpected response (such as invalid PDU * parameter). * * @author uudashr * @version 1.0 * @since 1.0 * */ public class InvalidResponseException extends Exception { private static final long serialVersionUID = -7149393390064407238L; /** * Construct with specified message and cause. * * @param message is the detail message. * @param cause is the parent cause. */ public InvalidResponseException(String message, Throwable cause) { super(message, cause); } /** * Construct with specified message. * * @param message is the detail message. */ public InvalidResponseException(String message) { super(message); } } jsmpp-2.1.2/src/main/java/org/jsmpp/MessageCoding.java000066400000000000000000000016421246113105100225710ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; /** * This is enum const that specified the message coding (see smpp spesification). * * @author uudashr * @version 1.0 * @since 1.0 * */ public enum MessageCoding { /** * Coding 7-bit. */ CODING_7_BIT, /** * Coding 8-bit. */ CODING_8_BIT, /** * Coding 16-bit. */ CODING_16_BIT; } jsmpp-2.1.2/src/main/java/org/jsmpp/PDUException.java000066400000000000000000000027341246113105100223730ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; /** * This exception is thrown when there is a failure corresponds to PDU processing. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class PDUException extends Exception { private static final long serialVersionUID = -4168434058788171394L; /** * Default constructor. */ public PDUException() { super("PDUException found"); } /** * Construct with specified message and cause. * * @param message is the detail message. * @param cause is the parent cause. */ public PDUException(String message, Throwable cause) { super(message, cause); } /** * Construct with specified message. * * @param message is the detail message. */ public PDUException(String message) { super(message); } /** * Construct with specified cause. * * @param cause is the parent cause. */ public PDUException(Throwable cause) { super(cause); } } jsmpp-2.1.2/src/main/java/org/jsmpp/PDUReader.java000066400000000000000000000046101246113105100216320ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import org.jsmpp.bean.Command; /** * Reader for SMPP PDU from specified {@link InputStream}. * * @author uudashr * @version 1.0 * @since 1.0 * */ public interface PDUReader { /** * Read the pdu header. If command length to short, we will read the left * bytes anyway, and throw {@link InvalidCommandLengthException} * * @param in is the input stream of the pdu. * @return the header of smpp command. * @throws InvalidCommandLengthException if command_length is to short. * @throws IOException if an I/O error occurs. */ public Command readPDUHeader(DataInputStream in) throws InvalidCommandLengthException, IOException; /** * Read all smpp pdu (excluding the command header) with specified pdu * header. * * @param in is input stream of the pdu (the source). * @param pduHeader is the pdu header. * @return the complete byte of smpp command. * @throws IOException if an I/O error occurs. */ public byte[] readPDU(InputStream in, Command pduHeader) throws IOException; /** * Read all smpp pdu (excluding the command header) with specified pdu * header values. * * @param in is the input stream of the pdu (the source). * @param commandLength is the command length of smpp pdu command. * @param commandId is id of smpp command. * @param commandStatus is status of smpp command. * @param sequenceNumber is sequence number of smpp command. * @return the complete byte of smpp command. * @throws IOException if an I/O error occurs. */ public byte[] readPDU(InputStream in, int commandLength, int commandId, int commandStatus, int sequenceNumber) throws IOException; }jsmpp-2.1.2/src/main/java/org/jsmpp/PDUSender.java000066400000000000000000000370571246113105100216630ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.bean.BindType; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.DestinationAddress; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.InterfaceVersion; import org.jsmpp.bean.MessageState; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.ReplaceIfPresentFlag; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.bean.UnsuccessDelivery; /** * This class provide way to send SMPP Command over an {@link OutputStream}. * PDU will be created and returned as bytes. * * @author uudashr * @version 1.0 * @since 1.0 * */ public interface PDUSender { /** * Send only the PDU header. * * @param os is the {@link OutputStream} * @param commandId is the SMPP command_id. * @param commandStatus is the SMPP command_status. * @param sequenceNumber is the SMPP sequence_number. * @return the composed bytes. * @throws IOException if an I/O error occur. */ byte[] sendHeader(OutputStream os, int commandId, int commandStatus, int sequenceNumber) throws IOException; /** * Send bind command. * * @param os is the {@link OutputStream} * @param bindType is the bind type that determine the command_id. * @param sequenceNumber is the sequence_number. * @param systemId is the system_id. * @param password is the password. * @param systemType is the system_type. * @param interfaceVersion is the interface_version. * @param addrTon is the addr_ton. * @param addrNpi is the addr_npi. * @param addressRange is the address_range. * @return the composed bytes. * @throws PDUStringException if there is an invalid string constraint found. * @throws IOException if an I/O error occur. */ byte[] sendBind(OutputStream os, BindType bindType, int sequenceNumber, String systemId, String password, String systemType, InterfaceVersion interfaceVersion, TypeOfNumber addrTon, NumberingPlanIndicator addrNpi, String addressRange) throws PDUStringException, IOException; /** * Send bind response command. * * @param os is the {@link OutputStream}. * @param commandId is the command_id. * @param sequenceNumber is the sequence_number. * @param systemId is the system_id. * @return the composed bytes. * @throws PDUStringException * @throws IOException if an IO error occur. */ byte[] sendBindResp(OutputStream os, int commandId, int sequenceNumber, String systemId) throws PDUStringException, IOException; /** * Send unbind command. * * @param os is the {@link OutputStream} . * @param sequenceNumber is the sequence_number. * @return the composed bytes. * @throws IOException if an IO error occur. */ byte[] sendUnbind(OutputStream os, int sequenceNumber) throws IOException; /** * Send generic non-acknowledge command. * * @param os is the {@link OutputStream} * @param commandStatus is the command_status. * @param sequenceNumber is the sequence_number. * @return the composed bytes. * @throws IOException if an IO error occur. */ byte[] sendGenericNack(OutputStream os, int commandStatus, int sequenceNumber) throws IOException; /** * Send unbind response command. * * @param os is the {@link OutputStream}. * @param commandStatus is the command_status. * @param sequenceNumber is the sequence_number. * @return the composed bytes. * @throws IOException if an IO error occur. */ byte[] sendUnbindResp(OutputStream os, int commandStatus, int sequenceNumber) throws IOException; /** * Send enquire link command. * * @param os is the {@link OutputStream}. * @param sequenceNumber is the sequence_number. * @return the composed bytes. * @throws IOException if an IO error occur. */ byte[] sendEnquireLink(OutputStream os, int sequenceNumber) throws IOException; /** * Send enquire link response command. * * @param os is the {@link OutputStream}. * @param sequenceNumber is the sequenceNumber. * @return the composed bytes. * @throws IOException if an IO error occur. */ byte[] sendEnquireLinkResp(OutputStream os, int sequenceNumber) throws IOException; /** * Send submit short message command. * * @param os is the {@link OutputStream}. * @param sequenceNumber is the sequence_number. * @param serviceType is the service_type. * @param sourceAddrTon is the source_addr_ton. * @param sourceAddrNpi is the source_addr_npi. * @param sourceAddr is the source_addr. * @param destAddrTon is the dest_addr_ton. * @param destAddrNpi is the dest_addr_npi. * @param destinationAddr is the destination_addr. * @param esmClass is the esm_class. * @param protocolId is the protocol_id. * @param priorityFlag is the priority_flag. * @param scheduleDeliveryTime is the schedule_delivery_time * @param validityPeriod is the validity_period. * @param registeredDelivery is the registered_delivery. * @param replaceIfPresentFlag is the replace_if_present_flag. * @param dataCoding is the data_coding. * @param smDefaultMsgId is the sm_default_msg_id. * @param shortMessage is the short_message. * @param optionalParameters is the optional parameters. * @return the composed bytes. * @throws PDUStringException if there is an invalid string constraint * found. * @throws IOException if there is an IO error occur. */ byte[] sendSubmitSm(OutputStream os, int sequenceNumber, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException, IOException; /** * Send submit short message response command. * * @param os is the {@link OutputStream}. * @param sequenceNumber is the sequence_number. * @param messageId is the message_id. * @return the composed bytes. * @throws PDUStringException if there is an invalid string constraint * found. * @throws IOException if there is an IO error occur. */ byte[] sendSubmitSmResp(OutputStream os, int sequenceNumber, String messageId) throws PDUStringException, IOException; /** * Send query short message command. * * @param os is the {@link OutputStream}. * @param sequenceNumber is the sequence_number. * @param messageId is the message_id. * @param sourceAddrTon is the source_addr_ton. * @param sourceAddrNpi is the source_addr_npi. * @param sourceAddr is the source_addr. * @return the composed bytes. * @throws PDUStringException if there is an invalid constraint found. * @throws IOException if there is an IO error occur. */ byte[] sendQuerySm(OutputStream os, int sequenceNumber, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr) throws PDUStringException, IOException; /** * Send query short message response command. * * @param os is the {@link OutputStream}. * @param sequenceNumber is the sequence_number. * @param messageId is the message_id. * @param finalDate is the final_date. * @param messageState is the message_state. * @param errorCode is the error_code. * @return the composed bytes. * @throws PDUStringException if there is an invalid constraint found. * @throws IOException if there is an IO error occur. */ byte[] sendQuerySmResp(OutputStream os, int sequenceNumber, String messageId, String finalDate, MessageState messageState, byte errorCode) throws PDUStringException, IOException; /** * Send the deliver short message command. * * @param os is the {@link OutputStream}. * @param sequenceNumber the sequence_number. * @param serviceType the service_type. * @param sourceAddrTon is the source_addr_ton. * @param sourceAddrNpi is the source_addr_npi. * @param sourceAddr is the source_addr. * @param destAddrTon is the dest_addr_ton. * @param destAddrNpi is the dest_addr_npi. * @param destinationAddr is the destination_addr. * @param esmClass is the esm_class. * @param protocoId is the protocol_id. * @param priorityFlag is the priority_flag. * @param registeredDelivery is the registered_delivery. * @param dataCoding is the data_coding. * @param shortMessage is the short_message. * @param optionalParameters is the optional parameters. * @return the composed bytes. * @throws PDUStringException if there is an invalid string constraint * found. * @throws IOException if there is an IO error occur. */ byte[] sendDeliverSm(OutputStream os, int sequenceNumber, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocoId, byte priorityFlag, RegisteredDelivery registeredDelivery, DataCoding dataCoding, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException, IOException; /** * Send the deliver short message response. * * @param os is the {@link OutputStream}. * @param sequenceNumber is the sequence_number. * @return the composed bytes. * @throws IOException if there is an IO error occur. */ byte[] sendDeliverSmResp(OutputStream os, int sequenceNumber) throws IOException; /** * Send the data short message command. * * @param os is the {@link OutputStream}. * @param sequenceNumber the sequence_number. * @param serviceType the service_type. * @param sourceAddrTon is the source_addr_ton. * @param sourceAddrNpi is the source_addr_npi. * @param sourceAddr is the source_addr. * @param destAddrTon is the dest_addr_ton. * @param destAddrNpi is the dest_addr_npi. * @param destinationAddr is the destination_addr. * @param esmClass is the esm_class. * @param registeredDelivery is the registered_delivery. * @param dataCoding is the data_coding. * @param optionalParameters is the optional parameters. * @return the composed bytes. * @throws PDUStringException if there is an invalid string constraint * found. * @throws IOException if there is an IO error occur. */ byte[] sendDataSm(OutputStream os, int sequenceNumber, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, RegisteredDelivery registeredDelivery, DataCoding dataCoding, OptionalParameter... optionalParameters) throws PDUStringException, IOException; /** * Send data short message response command. * * @param os is the {@link OutputStream}. * @param sequenceNumber is the sequence_number. * @param messageId is the message_id. * @param optionalParameters is the optional parameters. * @return the composed bytes. * @throws PDUStringException if there is an invalid string constraint * found. * @throws IOException if there is an IO error occur. */ byte[] sendDataSmResp(OutputStream os, int sequenceNumber, String messageId, OptionalParameter... optionalParameters) throws PDUStringException, IOException; /** * Send cancel short message command. * * @param os * @param sequenceNumber * @param serviceType * @param messageId * @param sourceAddrTon * @param sourceAddrNpi * @param sourceAddr * @param destAddrTon * @param destAddrNpi * @param destinationAddr * @return * @throws PDUStringException * @throws IOException */ byte[] sendCancelSm(OutputStream os, int sequenceNumber, String serviceType, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr) throws PDUStringException, IOException; /** * Send cancel short message response command. * * @param os * @param sequenceNumber * @return * @throws IOException */ byte[] sendCancelSmResp(OutputStream os, int sequenceNumber) throws IOException; byte[] sendReplaceSm(OutputStream os, int sequenceNumber, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte smDefaultMsgId, byte[] shortMessage) throws PDUStringException, IOException; byte[] sendReplaceSmResp(OutputStream os, int sequenceNumber) throws IOException; byte[] sendSubmiMulti(OutputStream os, int sequenceNumber, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, DestinationAddress[] destinationAddresses, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, ReplaceIfPresentFlag replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException, InvalidNumberOfDestinationsException, IOException; byte[] sendSubmitMultiResp(OutputStream os, int sequenceNumber, String messageId, UnsuccessDelivery... unsuccessDeliveries) throws PDUStringException, IOException; byte[] sendAlertNotification(OutputStream os, int sequenceNumber, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte esmeAddrTon, byte esmeAddrNpi, String esmeAddr, OptionalParameter... optionalParameters) throws PDUStringException, IOException; }jsmpp-2.1.2/src/main/java/org/jsmpp/PDUStringException.java000066400000000000000000000031501246113105100235530ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; import org.jsmpp.util.StringParameter; /** * Thrown if there is an invalid constraint for the PDU String parameter. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class PDUStringException extends PDUException { private static final long serialVersionUID = 5456303478921567516L; private StringParameter parameter; /** * Construct with specified message and parameter. * * @param message is the detail message. * @param parameter is the constraint parameter. */ public PDUStringException(String message, StringParameter parameter) { super(message); this.parameter = parameter; } /** * Get the constraint parameter. * * @return the constraint parameter. */ public StringParameter getParameter() { return parameter; } /** * Get the error code of the broken constaint. * * @return the command status should be returned. */ public int getErrorCode() { return parameter.getErrCode(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/SMPPConstant.java000066400000000000000000000327511246113105100223570ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; /** * This contains all of the smpp constants. *
    *
  • "CID" prefix is for command_id
  • *
  • "STAT" prefix is for command_status
  • *
* * @author uudashr * @version 1.0 * @version 1.0 * */ public interface SMPPConstant { /* * Untility constant */ /** * Is the MASK for the response command_id. */ public static final int MASK_CID_RESP = 0x80000000; /* * Command ID constants (CID prefix). */ public static final int CID_BIND_RECEIVER = 0x00000001; public static final int CID_BIND_TRANSMITTER = 0x00000002; public static final int CID_QUERY_SM = 0x00000003; public static final int CID_SUBMIT_SM = 0x00000004; public static final int CID_DELIVER_SM = 0x00000005; public static final int CID_UNBIND = 0x00000006; public static final int CID_REPLACE_SM = 0x00000007; public static final int CID_CANCEL_SM = 0x00000008; public static final int CID_BIND_TRANSCEIVER = 0x00000009; public static final int CID_OUTBIND = 0x0000000B; public static final int CID_ENQUIRE_LINK = 0x00000015; public static final int CID_SUBMIT_MULTI = 0x00000021; public static final int CID_ALERT_NOTIFICATION = 0x00000102; public static final int CID_DATA_SM = 0x00000103; public static final int CID_BROADCAST_SM = 0x00000111; public static final int CID_QUERY_BROADCAST_SM = 0x00000112; public static final int CID_CANCEL_BROADCAST_SM = 0x00000113; public static final int CID_GENERIC_NACK = 0x80000000; public static final int CID_BIND_RECEIVER_RESP = 0x80000001; public static final int CID_BIND_TRANSMITTER_RESP = 0x80000002; public static final int CID_QUERY_SM_RESP = 0x80000003; public static final int CID_SUBMIT_SM_RESP = 0x80000004; public static final int CID_DELIVER_SM_RESP = 0x80000005; public static final int CID_UNBIND_RESP = 0x80000006; public static final int CID_REPLACE_SM_RESP = 0x80000007; public static final int CID_CANCEL_SM_RESP = 0x80000008; public static final int CID_BIND_TRANSCEIVER_RESP = 0x80000009; public static final int CID_ENQUIRE_LINK_RESP = 0x80000015; public static final int CID_SUBMIT_MULTI_RESP = 0x80000021; public static final int CID_DATA_SM_RESP = 0x80000103; public static final int CID_BROADCAST_SM_RESP = 0x80000111; public static final int CID_QUERY_BROADCAST_SM_RESP = 0x80000112; public static final int CID_CANCEL_BROADCAST_SM_RESP = 0x80000113; /* * Command Status constants (STAT prefix). */ public static final int STAT_ESME_ROK = 0x00000000; public static final int STAT_ESME_RINVMSGLEN = 0x00000001; public static final int STAT_ESME_RINVCMDLEN = 0x00000002; public static final int STAT_ESME_RINVCMDID = 0x00000003; /** * Incorrect BIND Status for given command. *

* PDU has been sent in the wrong session state.
* E.g. sending a submit_sm without first establishing a Bound_TX session * state. */ public static final int STAT_ESME_RINVBNDSTS = 0x00000004; /** * ESME already in Bound State. */ public static final int STAT_ESME_RALYBND = 0x00000005; public static final int STAT_ESME_RINVPRTFLG = 0x00000006; public static final int STAT_ESME_RINVREGDLVFLG = 0x00000007; public static final int STAT_ESME_RSYSERR = 0x00000008; public static final int STAT_ESME_RINVSRCADR = 0x0000000A; public static final int STAT_ESME_RINVDSTADR = 0x0000000B; public static final int STAT_ESME_RINVMSGID = 0x0000000C; /** * Bind Failed. */ public static final int STAT_ESME_RBINDFAIL = 0x0000000D; public static final int STAT_ESME_RINVPASWD = 0x0000000E; public static final int STAT_ESME_RINVSYSID = 0x0000000F; public static final int STAT_ESME_RCANCELFAIL = 0x00000011; public static final int STAT_ESME_RREPLACEFAIL = 0x00000013; /** * Message queue full. */ public static final int STAT_ESME_RMSGQFUL = 0x00000014; public static final int STAT_ESME_RINVSERTYP = 0x00000015; public static final int STAT_ESME_RINVNUMDESTS = 0x00000033; public static final int STAT_ESME_RINVDLNAME = 0x00000034; public static final int STAT_ESME_RINVDESTFLAG = 0x00000040; public static final int STAT_ESME_RINVSUBREP = 0x00000042; public static final int STAT_ESME_RINVESMCLASS = 0x00000043; public static final int STAT_ESME_RCNTSUBDL = 0x00000044; public static final int STAT_ESME_RSUBMITFAIL = 0x00000045; public static final int STAT_ESME_RINVSRCTON = 0x00000048; public static final int STAT_ESME_RINVSRCNPI = 0x00000049; public static final int STAT_ESME_RINVDSTTON = 0x00000050; public static final int STAT_ESME_RINVDSTNPI = 0x00000051; public static final int STAT_ESME_RINVSYSTYP = 0x00000053; public static final int STAT_ESME_RINVREPFLAG = 0x00000054; public static final int STAT_ESME_RINVNUMMSGS = 0x00000055; public static final int STAT_ESME_RTHROTTLED = 0x00000058; public static final int STAT_ESME_RINVSCHED = 0x00000061; public static final int STAT_ESME_RINVEXPIRY = 0x00000062; /** * Predefined Message Invalid or Not Found. */ public static final int STAT_ESME_RINVDFTMSGID = 0x00000063; /** * ESME Receiver Temporary App Error Code */ public static final int STAT_ESME_RX_T_APPN = 0x00000064; /** * ESME Receiver Permanent App Error Code */ public static final int STAT_ESME_RX_P_APPN = 0x00000065; /** * ESME Receiver Reject App Error Code */ public static final int STAT_ESME_RX_R_APPN = 0x00000066; public static final int STAT_ESME_RQUERYFAIL = 0x00000067; public static final int STAT_ESME_RINVTLVSTREAM = 0x000000C0; public static final int STAT_ESME_RTLVNOTALLWD = 0x000000C1; public static final int STAT_ESME_RINVTLVLEN = 0x000000C2; public static final int STAT_ESME_RMISSINGTLV = 0x000000C3; public static final int STAT_ESME_RINVTLVVAL = 0x000000C4; public static final int STAT_ESME_RDELIVERYFAILURE = 0x000000FE; public static final int STAT_ESME_RUNKNOWNERR = 0x000000FF; public static final int STAT_ESME_RSERTYPUNAUTH = 0x00000100; public static final int STAT_ESME_RPROHIBITED = 0x00000101; public static final int STAT_ESME_RSERTYPUNAVAIL = 0x00000102; public static final int STAT_ESME_RSERTYPDENIED = 0x00000103; public static final int STAT_ESME_RINVDCS = 0x00000104; public static final int STAT_ESME_RINVSRCADDRSUBUNIT = 0x00000105; public static final int STAT_ESME_RINVDSTADDRSUBUNIT = 0x00000106; public static final int STAT_ESME_RINVBCASTFREQINT = 0x00000107; public static final int STAT_ESME_RINVBCASTALIAS_NAME = 0x00000108; public static final int STAT_ESME_RINVBCASTAREAFMT = 0x00000109; public static final int STAT_ESME_RINVNUMBCAST_AREAS = 0x0000010A; public static final int STAT_ESME_RINVBCASTCNTTYPE = 0x0000010B; public static final int STAT_ESME_RINVBCASTMSGCLASS = 0x0000010C; public static final int STAT_ESME_RBCASTFAIL = 0x0000010D; public static final int STAT_ESME_RBCASTQUERYFAIL = 0x0000010E; public static final int STAT_ESME_RBCASTCANCELFAIL = 0x0000010F; public static final int STAT_ESME_RINVBCAST_REP = 0x00000110; public static final int STAT_ESME_RINVBCASTSRVGRP = 0x00000111; public static final int STAT_ESME_RINVBCASTCHANIND = 0x00000112; /* * ESM class parameter constant */ // ESME -> SMSC Messaging Mode. public static final byte ESMCLS_DEFAULT_MODE = 0x00; public static final byte ESMCLS_DATAGRAM_MODE = 0x01; public static final byte ESMCLS_FORWARD_MODE = 0x02; public static final byte ESMCLS_STORE_FORWARD = 0x03; /** * Encoded esm_class parameter. xx0000xx */ public static final byte ESMCLS_DEFAULT_MESSAGE_TYPE = 0x00; // ESME -> SMSC Message Type. /** * Short Message contains ESME Delivery Acknowledgment. xx0010xx */ public static final byte ESMCLS_ESME_DELIVERY_ACK = 0x08; /** * Short Message contains ESME Manual/User Acknowledgment. xx0100xx */ public static final byte ESMCLS_ESME_MANUAL_ACK = 0x10; /** * Encoded esm_class parameter for deliver_sm or data_sm (SMSC -> ESME)
* xx0001xx Short Message contains SMSC Delivery Receipt. */ public static final byte ESMCLS_SMSC_DELIV_RECEIPT = 0x04; /** * Encoded esm_class parameter for deliver_sm or data_sm (SMSC -> ESME)
* xx0001xx Short Message contains SME Delivery Acknowledgment. */ public static final byte ESMCLS_SME_DELIV_ACK = 0x08; /** * Encoded esm_class parameter for deliver_sm or data_sm (SMSC -> ESME)
* xx0100xx Short Message contains SME Manual/User Acknowledgment. */ public static final byte ESMCLS_SME_MANUAL_ACK = 0x10; /** * Encoded esm_class parameter for deliver_sm or data_sm (SMSC -> ESME)
* xx0110xx Short Message contains Conversation Abort (Korean CDMA). */ public static final byte ESMCLS_CONV_ABORT = 0x18; /** * Encoded esm_class parameter for deliver_sm or data_sm (SMSC -> ESME)
* xx1000xx Short Message contains Intermediate Delivery Notification. */ public static final byte ESMCLS_INTRMD_DELIV_NOTIF = 0x20; /** * Encoded esm_class parameter for deliver_sm or data_sm (SMSC -> ESME)
* 01xxxxxx UDHI Indicator set. */ public static final byte ESMCLS_UDHI_INDICATOR_SET = 0x40; /** * Encoded esm_class parameter for deliver_sm or data_sm (SMSC -> ESME)
* 10xxxxxx Reply Path. */ public static final byte ESMCLS_REPLY_PATH = (byte)0x80; /** * Encoded esm_class parameter for deliver_sm or data_sm (SMSC -> ESME)
* 11xxxxxx UDHI and Reply Path can use. */ public static final byte ESMCLS_UDHI_REPLY_PATH = (byte)0xc0; /* * SMSC Delivery Receipt of registered delivery. bits 1 and 0 */ /** * No SMSC Delivery receipt. xxxxxx00 */ public static final byte REGDEL_SMSC_NO = 0x00; /** * SMSC Delivery Receipt requested where final delivery outcome is delivery * success or failure. xxxxxx01 */ public static final byte REGDEL_SMSC_SUCCESS_FAILURE_REQUESTED = 0x01; /** * SMSC Deliver Receipt requested where final delivery outcome is delivery * failure. xxxxxx10 */ public static final byte REGDEL_SMSC_FAILURE_REQUESTED = 0x02; /* * SME originated Acknowledgment of registered delivery. bits 3 and 2 */ /** * No recipient SME Acknowledgment requested. xxxx00xx */ public static final byte REGDEL_SME_ACK_NO = 0x00; /** * SME Delivery Acknowledgment requested. xxxx01xx */ public static final byte REGDEL_SME_DELIVERY_ACK_REQUESTED = 0x04; /** * SME Manual/User Acknowledgment requested. xxxx10xx */ public static final byte REGDEL_SME_MANUAL_ACK_REQUESTED = 0x08; /** * Both Delivery and Manual/User Acknowledgment requested. */ public static final byte REGDEL_SME_DELIVERY_MANUAL_ACK_REQUESTED = 0x0c; /* * Data Coding. */ /** * SMSC Default Alphabet. 00000000 */ public static final byte DC_DEFAULT = 0x00; /** * Octet unspecified (8-bit binary) */ public static final byte DC_BINARY = 0x04; /** * UCS2 (ISO/IEC-10646) 00001000 */ public static final byte DC_UCS2 = 0x08; /* * interface_version */ public static final byte IF_VERSION_33 = 0x33; public static final byte IF_VERSION_34 = 0x34; public static final byte IF_VERSION_50 = 0x50; /* * Type of Number */ public static final byte TON_UNKNOWN = 0x00; public static final byte TON_INTERNATIONAL = 0x01; public static final byte TON_NATIONAL = 0x02; public static final byte TON_NETWORK_SPECIFIC = 0x03; public static final byte TON_SUBSCRIBER_NUMBER = 0x04; public static final byte TON_ALPHANUMERIC = 0x05; public static final byte TON_ABBREVIATED = 0x06; /* * Numeric Plan Indicator */ public static final byte NPI_UNKNOWN = 0x00; public static final byte NPI_ISDN = 0x01; public static final byte NPI_DATA = 0x02; public static final byte NPI_TELEX = 0x03; public static final byte NPI_LAND_MOBILE = 0x04; public static final byte NPI_NATIONAL = 0x08; public static final byte NPI_PRIVATE = 0x09; public static final byte NPI_ERMES = 0x10; public static final byte NPI_INTERNET = 0x14; public static final byte NPI_WAP = 0x18; public static final short TAG_SC_INTERFACE_VERSION = 0x0210; public static final short TAG_SAR_MSG_REF_NUM = 0X020C; public static final short TAG_SAR_TOTAl_SEGMENTS = 0x020e; public static final short TAG_SAR_SEGMENT_SEQNUM = 0x020f; /* * Data Coding constants */ // Alphabet public static final byte MASK_ALPHA = 0x0f; public static final byte ALPHA_DEFAULT = 0x00; // 7-bit public static final byte ALPHA_UCS2 = 0x08; } jsmpp-2.1.2/src/main/java/org/jsmpp/SynchronizedPDUReader.java000066400000000000000000000046721246113105100242420ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import org.jsmpp.bean.Command; /** * This class id implementation of {@link PDUReader} that use synchronize when * accessing to the {@link InputStream} or {@link DataInputStream} tha used to * read the PDU. * * @author uudashr * @version 1.1 * @since 1.0 * */ public class SynchronizedPDUReader implements PDUReader { private final PDUReader pduReader; /** * Default constructor. */ public SynchronizedPDUReader() { this(new DefaultPDUReader()); } /** * Construct with specified pdu reader. * * @param pduReader is the pdu reader. */ public SynchronizedPDUReader(PDUReader pduReader) { this.pduReader = pduReader; } /* * (non-Javadoc) * * @see org.jsmpp.PDUReader#readPDU(java.io.InputStream, * org.jsmpp.bean.Command) */ public byte[] readPDU(InputStream in, Command pduHeader) throws IOException { synchronized (in) { return pduReader.readPDU(in, pduHeader); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUReader#readPDU(java.io.InputStream, int, int, * int, int) */ public byte[] readPDU(InputStream in, int commandLength, int commandId, int commandStatus, int sequenceNumber) throws IOException { synchronized (in) { return pduReader.readPDU(in, commandLength, commandId, commandStatus, sequenceNumber); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUReader#readPDUHeader(java.io.DataInputStream) */ public Command readPDUHeader(DataInputStream in) throws InvalidCommandLengthException, IOException { synchronized (in) { return pduReader.readPDUHeader(in); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/SynchronizedPDUSender.java000066400000000000000000000371431246113105100242570ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.bean.BindType; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.DestinationAddress; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.InterfaceVersion; import org.jsmpp.bean.MessageState; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.ReplaceIfPresentFlag; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.bean.UnsuccessDelivery; /** * PDU sender with synchronized the {@link OutputStream}. * * @author uudashr * @version 1.1 * @since 1.0 * */ public class SynchronizedPDUSender implements PDUSender { private final PDUSender pduSender; /** * Default constructor. */ public SynchronizedPDUSender() { this(new DefaultPDUSender()); } /** * Construct with specified {@link PDUSender}. * * @param pduSender */ public SynchronizedPDUSender(PDUSender pduSender) { this.pduSender = pduSender; } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendHeader(java.io.OutputStream, int, int, int) */ public byte[] sendHeader(OutputStream os, int commandId, int commandStatus, int sequenceNumber) throws IOException { synchronized (os) { return pduSender.sendHeader(os, commandId, commandStatus, sequenceNumber); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendBind(java.io.OutputStream, * org.jsmpp.BindType, int, java.lang.String, java.lang.String, * java.lang.String, org.jsmpp.InterfaceVersion, * org.jsmpp.TypeOfNumber, org.jsmpp.NumberingPlanIndicator, * java.lang.String) */ public byte[] sendBind(OutputStream os, BindType bindType, int sequenceNumber, String systemId, String password, String systemType, InterfaceVersion interfaceVersion, TypeOfNumber addrTon, NumberingPlanIndicator addrNpi, String addressRange) throws PDUStringException, IOException { synchronized (os) { return pduSender.sendBind(os, bindType, sequenceNumber, systemId, password, systemType, interfaceVersion, addrTon, addrNpi, addressRange); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendBindResp(java.io.OutputStream, int, int, * java.lang.String) */ public byte[] sendBindResp(OutputStream os, int commandId, int sequenceNumber, String systemId) throws PDUStringException, IOException { synchronized (os) { return pduSender.sendBindResp(os, commandId, sequenceNumber, systemId); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendUnbind(java.io.OutputStream, int) */ public byte[] sendUnbind(OutputStream os, int sequenceNumber) throws IOException { synchronized (os) { return pduSender.sendUnbind(os, sequenceNumber); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendGenericNack(java.io.OutputStream, int, int) */ public byte[] sendGenericNack(OutputStream os, int commandStatus, int sequenceNumber) throws IOException { synchronized (os) { return pduSender.sendGenericNack(os, commandStatus, sequenceNumber); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendUnbindResp(java.io.OutputStream, int, int) */ public byte[] sendUnbindResp(OutputStream os, int commandStatus, int sequenceNumber) throws IOException { synchronized (os) { return pduSender.sendUnbindResp(os, commandStatus, sequenceNumber); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendEnquireLink(java.io.OutputStream, int) */ public byte[] sendEnquireLink(OutputStream out, int sequenceNumber) throws IOException { synchronized (out) { return pduSender.sendEnquireLink(out, sequenceNumber); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendEnquireLinkResp(java.io.OutputStream, int) */ public byte[] sendEnquireLinkResp(OutputStream os, int sequenceNumber) throws IOException { synchronized (os) { return pduSender.sendEnquireLinkResp(os, sequenceNumber); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendSubmitSm(java.io.OutputStream, int, * java.lang.String, org.jsmpp.TypeOfNumber, * org.jsmpp.NumberingPlanIndicator, java.lang.String, * org.jsmpp.TypeOfNumber, org.jsmpp.NumberingPlanIndicator, * java.lang.String, org.jsmpp.bean.ESMClass, byte, byte, * java.lang.String, java.lang.String, * org.jsmpp.bean.RegisteredDelivery, byte, org.jsmpp.bean.DataCoding, * byte, byte[], org.jsmpp.bean.OptionalParameter[]) */ public byte[] sendSubmitSm(OutputStream os, int sequenceNumber, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte replaceIfPresent, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException, IOException { synchronized (os) { return pduSender.sendSubmitSm(os, sequenceNumber, serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, protocolId, priorityFlag, scheduleDeliveryTime, validityPeriod, registeredDelivery, replaceIfPresent, dataCoding, smDefaultMsgId, shortMessage, optionalParameters); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendSubmitSmResp(java.io.OutputStream, int, * java.lang.String) */ public byte[] sendSubmitSmResp(OutputStream os, int sequenceNumber, String messageId) throws PDUStringException, IOException { return pduSender.sendSubmitSmResp(os, sequenceNumber, messageId); } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendQuerySm(java.io.OutputStream, int, * java.lang.String, org.jsmpp.TypeOfNumber, * org.jsmpp.NumberingPlanIndicator, java.lang.String) */ public byte[] sendQuerySm(OutputStream os, int sequenceNumber, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr) throws PDUStringException, IOException { synchronized (os) { return pduSender.sendQuerySm(os, sequenceNumber, messageId, sourceAddrTon, sourceAddrNpi, sourceAddr); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendQuerySmResp(java.io.OutputStream, int, * java.lang.String, java.lang.String, org.jsmpp.bean.MessageState, * byte) */ public byte[] sendQuerySmResp(OutputStream os, int sequenceNumber, String messageId, String finalDate, MessageState messageState, byte errorCode) throws PDUStringException, IOException { synchronized (os) { return pduSender.sendQuerySmResp(os, sequenceNumber, messageId, finalDate, messageState, errorCode); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendDeliverSm(java.io.OutputStream, int, * java.lang.String, org.jsmpp.TypeOfNumber, * org.jsmpp.NumberingPlanIndicator, java.lang.String, * org.jsmpp.TypeOfNumber, org.jsmpp.NumberingPlanIndicator, * java.lang.String, org.jsmpp.bean.ESMClass, byte, byte, * org.jsmpp.bean.RegisteredDelivery, org.jsmpp.bean.DataCoding, * byte[], org.jsmpp.bean.OptionalParameter[]) */ public byte[] sendDeliverSm(OutputStream os, int sequenceNumber, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocoId, byte priorityFlag, RegisteredDelivery registeredDelivery, DataCoding dataCoding, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException, IOException { synchronized (os) { return pduSender.sendDeliverSm(os, sequenceNumber, serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, protocoId, priorityFlag, registeredDelivery, dataCoding, shortMessage, optionalParameters); } } public byte[] sendDeliverSmResp(OutputStream os, int sequenceNumber) throws IOException { synchronized (os) { return pduSender.sendDeliverSmResp(os, sequenceNumber); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendDataSm(java.io.OutputStream, int, * java.lang.String, org.jsmpp.TypeOfNumber, * org.jsmpp.NumberingPlanIndicator, java.lang.String, * org.jsmpp.TypeOfNumber, org.jsmpp.NumberingPlanIndicator, * java.lang.String, org.jsmpp.bean.ESMClass, * org.jsmpp.bean.RegisteredDelivery, org.jsmpp.bean.DataCoding, * org.jsmpp.bean.OptionalParameter[]) */ public byte[] sendDataSm(OutputStream os, int sequenceNumber, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, RegisteredDelivery registeredDelivery, DataCoding dataCoding, OptionalParameter... optionalParameters) throws PDUStringException, IOException { synchronized (os) { return pduSender.sendDataSm(os, sequenceNumber, serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, registeredDelivery, dataCoding, optionalParameters); } } /* * (non-Javadoc) * * @see org.jsmpp.PDUSender#sendDataSmResp(java.io.OutputStream, int, * java.lang.String, org.jsmpp.bean.OptionalParameter[]) */ public byte[] sendDataSmResp(OutputStream os, int sequenceNumber, String messageId, OptionalParameter... optionalParameters) throws PDUStringException, IOException { synchronized (os) { return pduSender.sendDataSmResp(os, sequenceNumber, messageId, optionalParameters); } } public byte[] sendCancelSm(OutputStream os, int sequenceNumber, String serviceType, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr) throws PDUStringException, IOException { synchronized (os) { return pduSender.sendCancelSm(os, sequenceNumber, serviceType, messageId, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr); } } public byte[] sendCancelSmResp(OutputStream os, int sequenceNumber) throws IOException { synchronized (os) { return pduSender.sendCancelSmResp(os, sequenceNumber); } } public byte[] sendReplaceSm(OutputStream os, int sequenceNumber, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte smDefaultMsgId, byte[] shortMessage) throws PDUStringException, IOException { synchronized (os) { return pduSender.sendReplaceSm(os, sequenceNumber, messageId, sourceAddrTon, sourceAddrNpi, sourceAddr, scheduleDeliveryTime, validityPeriod, registeredDelivery, smDefaultMsgId, shortMessage); } } public byte[] sendReplaceSmResp(OutputStream os, int sequenceNumber) throws IOException { synchronized (os) { return pduSender.sendReplaceSmResp(os, sequenceNumber); } } public byte[] sendSubmiMulti(OutputStream os, int sequenceNumber, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, DestinationAddress[] destinationAddresses, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, ReplaceIfPresentFlag replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException, InvalidNumberOfDestinationsException, IOException { synchronized (os) { return pduSender.sendSubmiMulti(os, sequenceNumber, serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destinationAddresses, esmClass, protocolId, priorityFlag, scheduleDeliveryTime, validityPeriod, registeredDelivery, replaceIfPresentFlag, dataCoding, smDefaultMsgId, shortMessage, optionalParameters); } } public byte[] sendSubmitMultiResp(OutputStream os, int sequenceNumber, String messageId, UnsuccessDelivery... unsuccessDeliveries) throws PDUStringException, IOException { synchronized (os) { return pduSender.sendSubmitMultiResp(os, sequenceNumber, messageId, unsuccessDeliveries); } } public byte[] sendAlertNotification(OutputStream os, int sequenceNumber, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte esmeAddrTon, byte esmeAddrNpi, String esmeAddr, OptionalParameter... optionalParameters) throws PDUStringException, IOException { synchronized (os) { return pduSender.sendAlertNotification(os, sequenceNumber, sourceAddrTon, sourceAddrNpi, sourceAddr, esmeAddrTon, esmeAddrNpi, esmeAddr, optionalParameters); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/000077500000000000000000000000001246113105100201205ustar00rootroot00000000000000jsmpp-2.1.2/src/main/java/org/jsmpp/bean/AbstractSmCommand.java000066400000000000000000000327641246113105100243410ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import java.util.Arrays; import org.jsmpp.SMPPConstant; /** * @author uudashr * */ public class AbstractSmCommand extends Command { protected String serviceType; protected byte sourceAddrTon; protected byte sourceAddrNpi; protected String sourceAddr; protected byte destAddrTon; protected byte destAddrNpi; protected String destAddress; protected byte esmClass; protected byte registeredDelivery; protected byte dataCoding; protected OptionalParameter[] optionalParametes; public AbstractSmCommand() { super(); } /** * Message Type. * * @return */ public boolean isDefaultMessageType() { return isDefaultMessageType(esmClass); } /** * Message Type. */ public void setDefaultMessageType() { esmClass = composeDefaultMessageType(esmClass); } /** * Specific Features. * * @return */ public boolean isUdhi() { return isUdhi(esmClass); } /** * Specific Features. */ public void setUdhi() { esmClass = composeUdhi(esmClass); } /** * Specific Features. * * @return */ public boolean isReplyPath() { return isReplyPath(esmClass); } /** * Specific Features. */ public void setReplyPath() { esmClass = composeReplyPath(esmClass); } /** * Specific Features. * * @return */ public boolean isUdhiAndReplyPath() { return isUdhiAndReplyPath(esmClass); } /** * Specific Features. */ public void setUdhiAndReplyPath() { esmClass = composeUdhiAndReplyPath(esmClass); } /** * @return the dataCoding */ public byte getDataCoding() { return dataCoding; } /** * @param dataCoding the dataCoding to set */ public void setDataCoding(byte dataCoding) { this.dataCoding = dataCoding; } public byte getDestAddrTon() { return destAddrTon; } public void setDestAddrTon(byte destAddrTon) { this.destAddrTon = destAddrTon; } public byte getDestAddrNpi() { return destAddrNpi; } public void setDestAddrNpi(byte destAddrNpi) { this.destAddrNpi = destAddrNpi; } public String getDestAddress() { return destAddress; } public void setDestAddress(String destAddress) { this.destAddress = destAddress; } /** * @return the esmClass */ public byte getEsmClass() { return esmClass; } /** * @param esmClass the esmClass to set */ public void setEsmClass(byte esmClass) { this.esmClass = esmClass; } /** * @return the registeredDelivery */ public byte getRegisteredDelivery() { return registeredDelivery; } /** * @param registeredDelivery the registeredDelivery to set */ public void setRegisteredDelivery(byte registeredDelivery) { this.registeredDelivery = registeredDelivery; } /** * @return the serviceType */ public String getServiceType() { return serviceType; } /** * @param serviceType the serviceType to set */ public void setServiceType(String serviceType) { this.serviceType = serviceType; } public OptionalParameter[] getOptionalParametes() { return optionalParametes; } public void setOptionalParametes(OptionalParameter... optionalParametes) { this.optionalParametes = optionalParametes; } public byte getSourceAddrTon() { return sourceAddrTon; } public void setSourceAddrTon(byte sourceAddrTon) { this.sourceAddrTon = sourceAddrTon; } public byte getSourceAddrNpi() { return sourceAddrNpi; } public void setSourceAddrNpi(byte sourceAddrNpi) { this.sourceAddrNpi = sourceAddrNpi; } public String getSourceAddr() { return sourceAddr; } public void setSourceAddr(String sourceAddr) { this.sourceAddr = sourceAddr; } /** * Message Type. Default message Type. * * @param esmClass * @return true if esmClass indicate delivery receipt */ public static boolean isDefaultMessageType(byte esmClass) { return isMessageType(esmClass, SMPPConstant.ESMCLS_DEFAULT_MESSAGE_TYPE); } /** * Message Type. Compose the esm_class as with default message Type. * * @param esmClass * @return */ public static byte composeDefaultMessageType(byte esmClass) { return cleanMessageType(esmClass); } /** * Specific Features. * * @param esmClass * @return */ public static boolean isUdhi(byte esmClass) { return isSpecificFeatures(esmClass, SMPPConstant.ESMCLS_UDHI_INDICATOR_SET); } /** * Specific Features. * * @param esmClass * @return */ public static byte composeUdhi(byte esmClass) { return composeSpecificFeatures(esmClass, SMPPConstant.ESMCLS_UDHI_INDICATOR_SET); } /** * Specific Features. * * @param esmClass * @return */ public static boolean isReplyPath(byte esmClass) { return isSpecificFeatures(esmClass, SMPPConstant.ESMCLS_REPLY_PATH); } /** * Specific Features. * * @param esmClass * @return */ public static byte composeReplyPath(byte esmClass) { return composeSpecificFeatures(esmClass, SMPPConstant.ESMCLS_REPLY_PATH); } /** * Specific Features. * * @param esmClass * @return */ public static boolean isUdhiAndReplyPath(byte esmClass) { return isSpecificFeatures(esmClass, SMPPConstant.ESMCLS_UDHI_REPLY_PATH); } /** * Specific Features. * * @param esmClass * @return */ public static byte composeUdhiAndReplyPath(byte esmClass) { return composeSpecificFeatures(esmClass, SMPPConstant.ESMCLS_UDHI_REPLY_PATH); } /* * Messaging Mode. */ protected final static boolean isMessagingMode(byte esmClass, byte messagingModeValue) { // 00000011 = 0x03 return (esmClass & 0x03) == messagingModeValue; } /** * Compose the Messaging Mode. Messaging Mode encoded on ESM Class at bits 1 - * 0. * * @param esmClass current/old ESM class. * @param messagingModeValue * @return the encoded messaging mode at ESM class */ protected final static byte composeMessagingMode(byte esmClass, byte messagingModeValue) { return (byte)(cleanMessagingMode(esmClass) | messagingModeValue); } /** * Clean the Messaging Mode or clean the ESM Class at bits 1 - 0. * * @param esmClass * @return */ protected final static byte cleanMessagingMode(byte esmClass) { /* * 00000011 = 0x03 * * esmClass & 0x03 -> will clear the bits 1 - 0 */ return (byte)(esmClass & 0x03); } /* * Message Type. */ protected final static boolean isMessageType(byte esmClass, byte messageTypeValue) { // 00111100 = 0x3c return (esmClass & 0x3c) == messageTypeValue; } /** * Compose the Message Type. Message Type encoded on ESM Class at bits 5 - * 2. * * @param esmClass * @param messageTypeValue * @return */ protected final static byte composeMessageType(byte esmClass, byte messageTypeValue) { return (byte)(cleanMessageType(esmClass) | messageTypeValue); } /** * Clean the Message Type or clean the ESM Class at bits 5 - 2. * * @param esmClass * @return */ protected final static byte cleanMessageType(byte esmClass) { /* * 11000011 = 0xc3 * * esmClass & 0xc3 -> will clear the bits 5 - 2 */ return (byte)(esmClass & 0xc3); } /* * Specific Features. */ protected final static boolean isSpecificFeatures(byte esmClass, byte specificFeaturesValue) { // 01000000 = 0xC0 return (esmClass & 0xC0) == specificFeaturesValue; } /** * Compose Specific Features. Specific Features encoded on ESM Class at bits * 7 - 6. * * @param esmClass * @param specificFeaturesValue * @return */ protected final static byte composeSpecificFeatures(byte esmClass, byte specificFeaturesValue) { return (byte)(cleanSpecificFeatures(esmClass) | specificFeaturesValue); } /** * Clean the Specific Features or ESM Class at bits 7 - 6. * * @param esmClass * @return */ protected final static byte cleanSpecificFeatures(byte esmClass) { /* * 00111111 = 0x3f * * esmClass & 0x3f -> will clear the bits 7 -6 */ return (byte)(esmClass & 0x3f); } /* * SMSC Delivert Receipt. */ /** * SMSC Delivery Receipt. * * @param registeredDelivery * @param smscDeliveryReceiptValue * @return */ protected static final boolean isSmscDeliveryReceipt( byte registeredDelivery, byte smscDeliveryReceiptValue) { // xxxxxx11 = 0x03 mask bits 1 - 0 return (registeredDelivery & 0x03) == smscDeliveryReceiptValue; } protected static final byte composeSmscDelReceipt(byte registeredDelivery, byte smscDeliveryReceiptValue) { return (byte)(cleanSmscDeliveryReceipt(registeredDelivery) | smscDeliveryReceiptValue); } protected static final byte cleanSmscDeliveryReceipt(byte registeredDelivery) { // 11111100 = 0x0fc return (byte)(registeredDelivery & 0x0fc); } /* * SME originated Acknowledgement. */ /** * SME originated Acknowledgement. * * @param registeredDeliery * @param smeOriginatedAckValue * @return */ protected static final boolean isSmeAck(byte registeredDeliery, byte smeOriginatedAckValue) { // xxxx11xx = 0x0c mask bits 3 - 2 return (registeredDeliery & 0x0c) == smeOriginatedAckValue; } protected static final byte composeSmeAck(byte registeredDelivery, byte smeOriginatedValue) { return (byte)(cleanSmeAck(registeredDelivery) | smeOriginatedValue); } protected static final byte cleanSmeAck(byte registeredDelivery) { // 11110011 = 0xf3 // (registeredDelivery & 0x0c) will clean the bits 3 - 2. return (byte)(registeredDelivery & 0x0c); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((destAddress == null) ? 0 : destAddress.hashCode()); result = prime * result + Arrays.hashCode(optionalParametes); result = prime * result + ((serviceType == null) ? 0 : serviceType.hashCode()); result = prime * result + ((sourceAddr == null) ? 0 : sourceAddr.hashCode()); return result; } private boolean hasEqualDestAddress(AbstractSmCommand other) { if (destAddress == null) { if (other.destAddress != null) return false; } return destAddress.equals(other.destAddress); } private boolean hasEqualSourceAddr(AbstractSmCommand other) { if (sourceAddr == null) { if (other.sourceAddr != null) return false; } return sourceAddr.equals(other.sourceAddr); } private boolean hasEqualServiceType(AbstractSmCommand other) { if (serviceType == null) { if (other.serviceType != null) return false; } return serviceType.equals(other.serviceType); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final AbstractSmCommand other = (AbstractSmCommand)obj; if (destAddrTon != other.destAddrTon) return false; if (destAddrNpi != other.destAddrNpi) return false; if (!hasEqualDestAddress(other)) { return false; } if (sourceAddrTon != other.sourceAddrTon) return false; if (sourceAddrNpi != other.sourceAddrNpi) return false; if (!hasEqualSourceAddr(other)) { return false; } if (dataCoding != other.dataCoding) return false; if (esmClass != other.esmClass) return false; if (!Arrays.equals(optionalParametes, other.optionalParametes)) return false; if (registeredDelivery != other.registeredDelivery) return false; if (!hasEqualServiceType(other)) { return false; } return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/AbstractSmRespCommand.java000066400000000000000000000034251246113105100251630ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class AbstractSmRespCommand extends Command { private String messageId; public AbstractSmRespCommand() { super(); } /** * @return Returns the messageId. */ public String getMessageId() { return messageId; } /** * @param messageId The messageId to set. */ public void setMessageId(String messageId) { this.messageId = messageId; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((messageId == null) ? 0 : messageId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final AbstractSmRespCommand other = (AbstractSmRespCommand)obj; if (messageId == null) { if (other.messageId != null) return false; } else if (!messageId.equals(other.messageId)) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/Address.java000066400000000000000000000071751246113105100223620ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * This are SME (Short Message Entity) Address. * * @author uudashr * */ public class Address implements DestinationAddress { private TypeOfNumber typeOfNumber; private NumberingPlanIndicator numberingPlanIndicator; private String address; public Address(TypeOfNumber typeOfNumber, NumberingPlanIndicator numberingPlanIndicator, String address) { this.typeOfNumber = typeOfNumber; this.numberingPlanIndicator = numberingPlanIndicator; this.address = address; } public Address(byte typeOfNumber, byte numberingPlanIndicator, String address) { this(TypeOfNumber.valueOf(typeOfNumber), NumberingPlanIndicator.valueOf(numberingPlanIndicator), address); } public Flag getFlag() { return Flag.SME_ADDRESS; } public TypeOfNumber getTypeOfNumber() { return typeOfNumber; } public byte getTon() { return typeOfNumber.value(); } public NumberingPlanIndicator getNumberingPlanIndicator() { return numberingPlanIndicator; } public byte getNpi() { return numberingPlanIndicator.value(); } public String getAddress() { return address; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((address == null) ? 0 : address.hashCode()); result = prime * result + ((numberingPlanIndicator == null) ? 0 : numberingPlanIndicator.hashCode()); result = prime * result + ((typeOfNumber == null) ? 0 : typeOfNumber.hashCode()); return result; } private boolean hasEqualAddress(Address other) { if (address == null) { if (other.address != null) { return false; } } return address.equals(other.address); } private boolean hasEqualNumberingPlanIndicator(Address other) { if (numberingPlanIndicator == null) { if (other.numberingPlanIndicator != null) { return false; } } return numberingPlanIndicator.equals(other.numberingPlanIndicator); } private boolean hasEqualTypeOfNumber(Address other) { if (typeOfNumber == null) { if (other.typeOfNumber != null) { return false; } } return typeOfNumber.equals(other.typeOfNumber); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Address other = (Address)obj; if (!hasEqualAddress(other)) { return false; } if (!hasEqualNumberingPlanIndicator(other)) { return false; } if (!hasEqualTypeOfNumber(other)) { return false; } return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/AlertNotification.java000066400000000000000000000077331246113105100244130ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import java.util.Arrays; /** * @author uudashr * */ public class AlertNotification extends Command { private byte sourceAddrTon; private byte sourceAddrNpi; private String sourceAddr; private byte esmeAddrTon; private byte esmeAddrNpi; private String esmeAddr; private OptionalParameter[] optionalParameters; public AlertNotification() { super(); } public byte getSourceAddrTon() { return sourceAddrTon; } public void setSourceAddrTon(byte sourceAddrTon) { this.sourceAddrTon = sourceAddrTon; } public byte getSourceAddrNpi() { return sourceAddrNpi; } public void setSourceAddrNpi(byte sourceAddrNpi) { this.sourceAddrNpi = sourceAddrNpi; } public String getSourceAddr() { return sourceAddr; } public void setSourceAddr(String sourceAddr) { this.sourceAddr = sourceAddr; } public byte getEsmeAddrTon() { return esmeAddrTon; } public void setEsmeAddrTon(byte esmeAddrTon) { this.esmeAddrTon = esmeAddrTon; } public byte getEsmeAddrNpi() { return esmeAddrNpi; } public void setEsmeAddrNpi(byte esmeAddrNpi) { this.esmeAddrNpi = esmeAddrNpi; } public String getEsmeAddr() { return esmeAddr; } public void setEsmeAddr(String esmeAddr) { this.esmeAddr = esmeAddr; } public OptionalParameter[] getOptionalParameters() { return optionalParameters; } public void setOptionalParameters(OptionalParameter[] optionalParameters) { this.optionalParameters = optionalParameters; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((esmeAddr == null) ? 0 : esmeAddr.hashCode()); result = prime * result + Arrays.hashCode(optionalParameters); result = prime * result + ((sourceAddr == null) ? 0 : sourceAddr.hashCode()); return result; } private boolean hasEqualSourceAddr(AlertNotification other) { if (sourceAddr == null) { if (other.sourceAddr != null) { return false; } } return sourceAddr.equals(other.sourceAddr); } private boolean hasEqualEsmeAddr(AlertNotification other) { if (esmeAddr == null) { if (other.esmeAddr != null) { return false; } } return esmeAddr.equals(other.esmeAddr); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final AlertNotification other = (AlertNotification)obj; if (!hasEqualEsmeAddr(other)) { return false; } if (esmeAddrNpi != other.esmeAddrNpi) return false; if (esmeAddrTon != other.esmeAddrTon) return false; if (!Arrays.equals(optionalParameters, other.optionalParameters)) return false; if (!hasEqualSourceAddr(other)) { return false; } if (sourceAddrNpi != other.sourceAddrNpi) return false; if (sourceAddrTon != other.sourceAddrTon) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/Alphabet.java000066400000000000000000000041221246113105100225020ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * This is enum of the alphabet type. * * @author uudashr * @version 1.0 * */ public enum Alphabet { /** * SMSC alphabet default */ ALPHA_DEFAULT((byte)0x00), /** * The -bit aphabet coding. */ ALPHA_8_BIT((byte)0x04), /** * UCS2 alphabet coding (16-bit) */ ALPHA_UCS2((byte)0x08), /** * Unused. */ ALPHA_RESERVED((byte)0x0c); /** * Is the MASK of alphabet (00001100). */ public static final byte MASK_ALPHABET = 0x0c; // bin: 00001100 private final byte value; /** * Default constructor. * * @param value is the alphabet value. */ private Alphabet(byte value) { this.value = value; } /** * Get the alphabet value. * * @return the alphabet value. */ public byte value() { return value; } /** * Get the enum constant associated with specified value. * * @param value is the value associated with the Alphabet enum * constant. * @return the associated enum constant. * @throws IllegalArgumentException if there is no associated enum constant * for given value. */ public static Alphabet valueOf(byte value) throws IllegalArgumentException { for (Alphabet val : values()) { if (val.value == value) return val; } throw new IllegalArgumentException("No enum const Alphabet with value " + value); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/Bind.java000066400000000000000000000131321246113105100216370ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * This class represent SMPP bind command. * * @author uudashr * @version 1.0 * */ public class Bind extends Command { private String systemId; private String password; private String systemType; private byte interfaceVersion; private byte addrTon; private byte addrNpi; private String addressRange; public Bind() { super(); } /** * Get the address_range. * * @return the address_range. */ public String getAddressRange() { return addressRange; } /** * Set the address_range. * * @param addressRange is the address_range. */ public void setAddressRange(String addressRange) { this.addressRange = addressRange; } /** * Get the addr_npi. * * @return the addr_npi. */ public byte getAddrNpi() { return addrNpi; } /** * Set the addr_npi. * * @param addrNpi is the addr_npi. */ public void setAddrNpi(byte addrNpi) { this.addrNpi = addrNpi; } /** * Get the addr_ton. * * @return the addr_ton. */ public byte getAddrTon() { return addrTon; } /** * Set the addr_ton. * * @param addrTon is the addr_ton. */ public void setAddrTon(byte addrTon) { this.addrTon = addrTon; } /** * Get the interface_version. * * @return the interface_version. */ public byte getInterfaceVersion() { return interfaceVersion; } /** * Set the interface_version. * * @param interfaceVersion is the interface_version. */ public void setInterfaceVersion(byte interfaceVersion) { this.interfaceVersion = interfaceVersion; } /** * Get the password. * * @return the password. */ public String getPassword() { return password; } /** * Set the password. * * @param password is the password. */ public void setPassword(String password) { this.password = password; } /** * Get the system_id. * * @return the system_id. */ public String getSystemId() { return systemId; } /** * Set the system_id. * * @param systemId is the system_id. */ public void setSystemId(String systemId) { this.systemId = systemId; } /** * Get the system_type. * * @return the system_type. */ public String getSystemType() { return systemType; } /** * Set the system_type. * * @param systemType is the system_type. */ public void setSystemType(String systemType) { this.systemType = systemType; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((addressRange == null) ? 0 : addressRange.hashCode()); result = prime * result + ((password == null) ? 0 : password.hashCode()); result = prime * result + ((systemId == null) ? 0 : systemId.hashCode()); result = prime * result + ((systemType == null) ? 0 : systemType.hashCode()); return result; } private boolean hasEqualAddressRange(Bind other) { if (addressRange == null) { if (other.addressRange != null) { return false; } } return addressRange.equals(other.addressRange); } private boolean hasEqualPassword(Bind other) { if (password == null) { if (other.password != null) { return false; } } return password.equals(other.password); } private boolean hasEqualSystemId(Bind other) { if (systemId == null) { if (other.systemId != null) { return false; } } return systemId.equals(other.systemId); } private boolean hasEqualSystemType(Bind other) { if (systemType == null) { if (other.systemType != null) { return false; } } return systemType.equals(other.systemType); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final Bind other = (Bind)obj; if (addrNpi != other.addrNpi) return false; if (addrTon != other.addrTon) return false; if (!hasEqualAddressRange(other)) { return false; } if (interfaceVersion != other.interfaceVersion) return false; if (!hasEqualPassword(other)) { return false; } if (!hasEqualSystemId(other)) { return false; } if (!hasEqualSystemType(other)) { return false; } return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/BindResp.java000066400000000000000000000045641246113105100225020ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import java.util.Arrays; /** * This class represent SMPP bind response command. * * @author uudashr * @version 1.0 * */ public class BindResp extends Command { private String systemId; private OptionalParameter[] optionalParameters; /** * Default constructor. */ public BindResp() { super(); } /** * Get the system_id. * * @return the system_id. */ public String getSystemId() { return systemId; } /** * Set the system_id. * * @param systemId is the system_id. */ public void setSystemId(String systemId) { this.systemId = systemId; } public OptionalParameter[] getOptionalParameters() { return optionalParameters; } public void setOptionalParameters(OptionalParameter[] optionalParameters) { this.optionalParameters = optionalParameters; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Arrays.hashCode(optionalParameters); result = prime * result + ((systemId == null) ? 0 : systemId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final BindResp other = (BindResp)obj; if (!Arrays.equals(optionalParameters, other.optionalParameters)) return false; if (systemId == null) { if (other.systemId != null) return false; } else if (!systemId.equals(other.systemId)) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/BindType.java000066400000000000000000000060151246113105100225030ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.SMPPConstant; /** * Enum represent bind type of SMPP. There is 3 bind type provide by SMPP: *

    *
  • receiver (BIND_RX) - receive only
  • *
  • transmitter (BIND_TX) - transmit only
  • *
  • transceiver (BIND_TRX) - receive and transmit
  • *
* * @author uudashr * @version 1.0 * @since 1.0 * */ public enum BindType { /** * Bind transmitter. */ BIND_TX(SMPPConstant.CID_BIND_TRANSMITTER), /** * Bind receiver. */ BIND_RX(SMPPConstant.CID_BIND_RECEIVER), /** * Bind transceiver. */ BIND_TRX(SMPPConstant.CID_BIND_TRANSCEIVER); private int bindCommandId; private BindType(int bindCommadId) { this.bindCommandId = bindCommadId; } /** * Get the command_id of given bind type. * * @return the bind command_id. */ public int commandId() { return bindCommandId; } /** * Return the response command_id that should given by this bind type. * * @return the bind response command_id. */ public int responseCommandId() { return bindCommandId | SMPPConstant.MASK_CID_RESP; } /** * Inform whether the bind type is transmitable. * * @return true f the bind type is transmitable, otherwise * false. */ public boolean isTransmitable() { return this == BIND_TX || this == BIND_TRX; } /** * Inform whether the bind type is receivable. * * @return true if the bind type is receivable, otherwise * false. */ public boolean isReceiveable() { return this == BIND_RX || this == BIND_TRX; } /** * Get the BindType by specified command_id. * * @param bindCommandId is the command_id. * @return the enum const associated with the specified * bindCommandId. * @throws IllegalArgumentException if there is no BindType * associated with specified bindCommandId found. */ public static final BindType valueOf(int bindCommandId) throws IllegalArgumentException { for (BindType bindType : values()) { if (bindType.bindCommandId == bindCommandId) { return bindType; } } throw new IllegalArgumentException( "No enum const BindType with command id " + bindCommandId); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/CancelSm.java000066400000000000000000000114621246113105100224540ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class CancelSm extends Command { private String serviceType; private String messageId; private byte sourceAddrTon; private byte sourceAddrNpi; private String sourceAddr; private byte destAddrTon; private byte destAddrNpi; private String destinationAddress; public CancelSm() { super(); } public String getServiceType() { return serviceType; } public void setServiceType(String serviceType) { this.serviceType = serviceType; } public String getMessageId() { return messageId; } public void setMessageId(String messageId) { this.messageId = messageId; } public byte getSourceAddrTon() { return sourceAddrTon; } public void setSourceAddrTon(byte sourceAddrTon) { this.sourceAddrTon = sourceAddrTon; } public byte getSourceAddrNpi() { return sourceAddrNpi; } public void setSourceAddrNpi(byte sourceAddrNpi) { this.sourceAddrNpi = sourceAddrNpi; } public String getSourceAddr() { return sourceAddr; } public void setSourceAddr(String sourceAddr) { this.sourceAddr = sourceAddr; } public byte getDestAddrTon() { return destAddrTon; } public void setDestAddrTon(byte destAddrTon) { this.destAddrTon = destAddrTon; } public byte getDestAddrNpi() { return destAddrNpi; } public void setDestAddrNpi(byte destAddrNpi) { this.destAddrNpi = destAddrNpi; } public String getDestinationAddress() { return destinationAddress; } public void setDestinationAddress(String destAddress) { this.destinationAddress = destAddress; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((destinationAddress == null) ? 0 : destinationAddress .hashCode()); result = prime * result + ((messageId == null) ? 0 : messageId.hashCode()); result = prime * result + ((serviceType == null) ? 0 : serviceType.hashCode()); result = prime * result + ((sourceAddr == null) ? 0 : sourceAddr.hashCode()); return result; } private boolean hasEqualDestAddress(CancelSm other) { if (destinationAddress == null) { if (other.destinationAddress != null) return false; } return destinationAddress.equals(other.destinationAddress); } private boolean hasEqualServiceType(CancelSm other) { if (serviceType == null) { if (other.serviceType != null) { return false; } } return serviceType.equals(other.serviceType); } private boolean hasEqualSourceAddr(CancelSm other) { if (sourceAddr == null) { if (other.sourceAddr != null) { return false; } } return sourceAddr.equals(other.sourceAddr); } private boolean hasEqualMessageId(CancelSm other) { if (messageId == null) { if (other.messageId != null) return false; } return messageId.equals(other.messageId); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final CancelSm other = (CancelSm)obj; if (destAddrNpi != other.destAddrNpi) return false; if (destAddrTon != other.destAddrTon) return false; if (!hasEqualDestAddress(other)) { return false; } if (!hasEqualMessageId(other)) { return false; } if (!hasEqualServiceType(other)) { return false; } if (sourceAddrNpi != other.sourceAddrNpi) return false; if (sourceAddrTon != other.sourceAddrTon) return false; if (!hasEqualSourceAddr(other)) { return false; } return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/CancelSmResp.java000066400000000000000000000013261246113105100233040ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class CancelSmResp extends Command { public CancelSmResp() { super(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/Command.java000066400000000000000000000102241246113105100223400ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.util.IntUtil; /** * Class represent SMPP Command. Contains only the header of SMPP PDU. * * @author uudashr * @version 1.0 * */ public class Command { protected int commandLength; protected int commandId; protected int commandStatus; protected int sequenceNumber; /** * Default constructor. */ public Command() { } /** * Get the command_id. * * @return the command_id. */ public int getCommandId() { return commandId; } /** * Get the command_id as hex string value. * * @return the hex string value of command_id. */ public String getCommandIdAsHex() { return IntUtil.toHexString(commandId); } /** * Set the command_id. * * @param commandId is the new value of command_id.. */ public void setCommandId(int commandId) { this.commandId = commandId; } /** * Get the command_length. * * @return the command_length. */ public int getCommandLength() { return commandLength; } /** * Ser the command_length. * * @param commandLength is the new value of command_length. */ public void setCommandLength(int commandLength) { this.commandLength = commandLength; } /** * Get the command_status. * * @return the command_status. */ public int getCommandStatus() { return commandStatus; } /** * Get the command_status as hex string. * * @return the hex string value of command_status. */ public String getCommandStatusAsHex() { return IntUtil.toHexString(commandStatus); } /** * Set value of command_status. * * @param commandStatus is the new value of command_status. */ public void setCommandStatus(int commandStatus) { this.commandStatus = commandStatus; } /** * Get the sequence_number. * * @return the value of sequence_number. */ public int getSequenceNumber() { return sequenceNumber; } /** * Set value of sequence_number. * * @param sequenceNumber is the new value of sequece_number. */ public void setSequenceNumber(int sequenceNumber) { this.sequenceNumber = sequenceNumber; } @Override public String toString() { return "PDUHeader(" + commandLength + ", " + getCommandIdAsHex() + ", " + getCommandStatusAsHex() + ", " + sequenceNumber + ")"; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + commandId; result = PRIME * result + commandLength; result = PRIME * result + commandStatus; result = PRIME * result + sequenceNumber; return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Command other = (Command)obj; if (commandId != other.commandId) return false; if (commandLength != other.commandLength) return false; if (commandStatus != other.commandStatus) return false; if (sequenceNumber != other.sequenceNumber) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/DataCoding.java000066400000000000000000000054641246113105100227710ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * This is class of DataCoding * * @author uudashr * @version 1.0 * */ public abstract class DataCoding { /** * Create new instance of data coding with specified value. * * @param value is the value. * @return the DataCoding based on specified value. */ public static final DataCoding newInstance(int value) { byte byteValue = (byte) value; if (GeneralDataCoding.isCompatible(byteValue)) { return new GeneralDataCoding(byteValue); } else if (DataCoding1111.isCompatible(byteValue)) { return new DataCoding1111(byteValue); } else { return null; } } /** * Create new instance of data coding with specified value. * * @param value is the value. * @return DataCoding based on specified value. */ public static final DataCoding newInstance(byte value) { if (GeneralDataCoding.isCompatible(value)) { return new GeneralDataCoding(value); } else if (DataCoding1111.isCompatible(value)) { return new DataCoding1111(value); } else { return null; } } protected byte value; /** * Default constructor. */ public DataCoding() { value = 0; } /** * Construct with specified value. * * @param value is the data coding value. */ public DataCoding(int value) { this.value = (byte) value; } /** * Construct with specified value. * * @param value is the data coding value. */ public DataCoding(byte value) { this.value = value; } /** * Get the value of data coding. * * @return the data coding value. */ public byte value() { return value; } @Override public int hashCode() { return 1; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final DataCoding other = (DataCoding)obj; if (value != other.value) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/DataCoding1111.java000066400000000000000000000065201246113105100232670ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * Data Coding with coding group bits 7..4 -> 1111 * * @author uudashr * @version 1.0 * */ public class DataCoding1111 extends DataCoding { private static final byte MASK_CODING_GROUP = (byte)0xf0; // 11110000 private static final byte MASK_MESSAGE_CLASS = MessageClass.MASK_MESSAGE_CLASS; private static final byte MASK_ALPHABET = Alphabet.MASK_ALPHABET; /** * Default constructor. */ public DataCoding1111() { super(); } /** * Construct with specified value. * * @param value is the value. */ public DataCoding1111(byte value) { super(value); } public DataCoding1111(Alphabet alphabet, MessageClass messageClass) { super(); setAlphabet(alphabet); setMessageClass(messageClass); } /** * Construct with specified value. * * @param value is the value. */ public DataCoding1111(int value) { super(value); } /** * Get the message class of current data coding. * * @return the {@link MessageClass}. */ public MessageClass getMessageClass() { return MessageClass.valueOf((byte)(value & MASK_MESSAGE_CLASS)); } /** * Compose data coding with specified message class. * * @param messageClass is the message class. */ public void setMessageClass(MessageClass messageClass) { byte tmp = cleanMessageClass(value); value = (byte)(tmp | messageClass.value()); } /** * Clean the message class bytes. * * @param value is the source of message class to clean. * @return the value without message class bytes. */ private static final byte cleanMessageClass(byte value) { return (byte)(value & (MASK_MESSAGE_CLASS ^ 0xff)); } /** * Get the alphabet value. * * @return the alphabet value. */ public Alphabet getAlphabet() { return Alphabet.valueOf((byte)(value & MASK_ALPHABET)); } /** * Compose data coding with specified alphabet. * * @param alphabet is the {@link Alphabet} */ public void setAlphabet(Alphabet alphabet) { byte tmp = cleanAlphabet(value); value = (byte)(tmp | alphabet.value()); } /** * Clean the alphabet bytes. * * @param value is the value of data coding to clean. * @return the clean data coding. */ private static final byte cleanAlphabet(byte value) { return (byte)(value & (MASK_ALPHABET ^ 0xff)); } public static boolean isCompatible(byte dataCodingValue) { return (dataCodingValue & MASK_CODING_GROUP) == MASK_CODING_GROUP; } @Override public String toString() { return "DataCoding111-" + value; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/DataSm.java000066400000000000000000000013211246113105100221310ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class DataSm extends AbstractSmCommand { public DataSm() { super(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/DataSmResp.java000066400000000000000000000032241246113105100227670ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import java.util.Arrays; /** * @author uudashr * */ public class DataSmResp extends AbstractSmRespCommand { private OptionalParameter[] optionalParameters; public DataSmResp() { super(); } public OptionalParameter[] getOptionalParameters() { return optionalParameters; } public void setOptionalParameters(OptionalParameter[] optionalParameters) { this.optionalParameters = optionalParameters; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Arrays.hashCode(optionalParameters); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final DataSmResp other = (DataSmResp)obj; if (!Arrays.equals(optionalParameters, other.optionalParameters)) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/DeliverSm.java000066400000000000000000000204011246113105100226520ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.SMPPConstant; import org.jsmpp.util.DefaultDecomposer; import org.jsmpp.util.InvalidDeliveryReceiptException; /** * @author uudashr * */ public class DeliverSm extends MessageRequest { public DeliverSm() { super(); } /** * Get the short message as {@link DeliveryReceipt}. This method will be * valid if the parsed short message valid and Message Type (esm_class) * contains SMSC Delivery Receipt. * * @return the {@link DeliveryReceipt}. * @throws InvalidDeliveryReceiptException */ public DeliveryReceipt getShortMessageAsDeliveryReceipt() throws InvalidDeliveryReceiptException { if (MessageType.SMSC_DEL_RECEIPT.containedIn(getEsmClass())) { return DefaultDecomposer.getInstance(). deliveryReceipt(getShortMessage()); } else { throw new InvalidDeliveryReceiptException("deliver_sm is not a Delivery Receipt since ems_class value = " + getEsmClass()); } } /** * Message Type. * @return */ public boolean isSmscDeliveryReceipt() { return isSmscDeliveryReceipt(esmClass); } /** * Message Type. * @param value */ public void setSmscDeliveryReceipt() { esmClass = composeSmscDeliveryReceipt(esmClass); } /** * Message Type. * @return */ public boolean isSmeManualAcknowledgment() { return isSmeManualAcknowledgment(esmClass); } /** * Message Type. */ public void setSmeManualAcknowledgment() { esmClass = composeSmeManualAcknowledment(esmClass); } /** * Message Type. * @return */ public boolean isConversationAbort() { return isConversationAbort(esmClass); } /** * Message Type. */ public void setConversationAbort() { esmClass = composeConversationAbort(esmClass); } /** * Message Type. * @return */ public boolean isIntermedietDeliveryNotification() { return isIntermedietDeliveryNotification(esmClass); } /** * Message Type. */ public void setIntermedietDeliveryNotification() { esmClass = composeIntermedietDeliveryNotification(esmClass); } /** * SME originated Acknowledgment. * @return */ public boolean isSmeAckNotRequested() { return isSmeAckNotRequested(registeredDelivery); } /** * SME originated Acknowledgment. */ public void setSmeAckNotRequested() { registeredDelivery = composeSmeAckNotRequested(registeredDelivery); } /** * SME originated Acknowledgment. * @return */ public boolean isSmeDeliveryAckRequested() { return isSmeDeliveryAckRequested(registeredDelivery); } /** * SME originated Acknowledgment. */ public void setSmeDeliveryAckRequested() { registeredDelivery = composeSmeDeliveryAckRequested(registeredDelivery); } /** * SME originated Acknowledgement. * @return */ public boolean isSmeManualAckRequested() { return isSmeManualAckRequested(registeredDelivery); } /** * * SME originated Acknowledgement. */ public void setSmeManualAckRequested() { registeredDelivery = composeSmeManualAckRequested(registeredDelivery); } /** * SME originated Acknowledgement. * @return */ public boolean isSmeDeliveryAndManualAckRequested() { return isSmeDeliveryAndManualAckRequested(registeredDelivery); } /** * SME originated Acknowledgement. */ public void setSmeDeliveryAndManualAckRequested() { registeredDelivery = composeSmeDeliveryAndManualAckRequested(registeredDelivery); } /** * Message Type. * Return esm_class of deliver_sm or data_sm indicate delivery receipt or not. * @param esmClass * @return true if esmClass indicate delivery receipt */ public static final boolean isSmscDeliveryReceipt(byte esmClass) { return isMessageType(esmClass, SMPPConstant.ESMCLS_SMSC_DELIV_RECEIPT); } /** * Message Type. * Set esm_class as delivery receipt * @param esmClass * @return */ public static final byte composeSmscDeliveryReceipt(byte esmClass) { return composeMessageType(esmClass, SMPPConstant.ESMCLS_SMSC_DELIV_RECEIPT); } /** * Message Type. * @param esmClass * @return */ public static final boolean isSmeDeliveryAcknowledgment(byte esmClass) { return isMessageType(esmClass, SMPPConstant.ESMCLS_SME_DELIV_ACK); } /** * Message Type. * @param esmClass * @return */ public static final byte composeSmeDeliveryAcknowledment(byte esmClass) { return composeMessageType(esmClass, SMPPConstant.ESMCLS_SME_DELIV_ACK); } /** * Message Type. * @param esmClass * @return */ public static final boolean isSmeManualAcknowledgment(byte esmClass) { return isMessageType(esmClass, SMPPConstant.ESMCLS_SME_MANUAL_ACK); } /** * Message Type. * @param esmClass * @return */ public static final byte composeSmeManualAcknowledment(byte esmClass) { return composeMessageType(esmClass, SMPPConstant.ESMCLS_SME_MANUAL_ACK); } /** * Message Type. * @param esmClass * @return */ public static final boolean isConversationAbort(byte esmClass) { return isMessageType(esmClass, SMPPConstant.ESMCLS_CONV_ABORT); } /** * Message Type. * @param esmClass * @return */ public static final byte composeConversationAbort(byte esmClass) { return composeMessageType(esmClass, SMPPConstant.ESMCLS_CONV_ABORT); } /** * Message Type. * @param esmClass * @return */ public static final boolean isIntermedietDeliveryNotification(byte esmClass) { return isMessageType(esmClass, SMPPConstant.ESMCLS_INTRMD_DELIV_NOTIF); } /** * Message Type. * @param esmClass * @return */ public static final byte composeIntermedietDeliveryNotification(byte esmClass) { return composeMessageType(esmClass, SMPPConstant.ESMCLS_INTRMD_DELIV_NOTIF); } /* * SME originated Acknowledgement. */ /** * SME originated Acknowledgement. * @param registeredDeliery * @return */ public static final boolean isSmeAckNotRequested(byte registeredDeliery) { return isSmeAck(registeredDeliery, SMPPConstant.REGDEL_SME_ACK_NO); } /** * SME originated Acknowledgment. * @param registeredDelivery * @return */ public static final byte composeSmeAckNotRequested(byte registeredDelivery) { return composeSmeAck(registeredDelivery, SMPPConstant.REGDEL_SME_ACK_NO); } /** * SME originated Acknowledgment. * @param registeredDeliery * @return */ public static final boolean isSmeDeliveryAckRequested(byte registeredDeliery) { return isSmeAck(registeredDeliery, SMPPConstant.REGDEL_SME_DELIVERY_ACK_REQUESTED); } /** * SME originated Acknowledgment. * @param registeredDelivery * @return */ public static final byte composeSmeDeliveryAckRequested(byte registeredDelivery) { return composeSmeAck(registeredDelivery, SMPPConstant.REGDEL_SME_DELIVERY_ACK_REQUESTED); } /** * SME originated Acknowledgment. * @param registeredDelivery * @return */ public static final boolean isSmeManualAckRequested(byte registeredDelivery) { return isSmeAck(registeredDelivery, SMPPConstant.REGDEL_SME_MANUAL_ACK_REQUESTED); } /** * SME originated Acknowledgment. * @param registeredDelivery * @return */ public static final byte composeSmeManualAckRequested(byte registeredDelivery) { return composeSmeAck(registeredDelivery, SMPPConstant.REGDEL_SME_MANUAL_ACK_REQUESTED); } /** * SME originated Acknowledgment. * @param registeredDelivery * @return */ public static final boolean isSmeDeliveryAndManualAckRequested(byte registeredDelivery) { return isSmeAck(registeredDelivery, SMPPConstant.REGDEL_SME_DELIVERY_MANUAL_ACK_REQUESTED); } /** * SME originated Acknowledgment. * @param registeredDelivery * @return */ public static final byte composeSmeDeliveryAndManualAckRequested(byte registeredDelivery) { return composeSmeAck(registeredDelivery, SMPPConstant.REGDEL_SME_DELIVERY_MANUAL_ACK_REQUESTED); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/DeliverSmResp.java000066400000000000000000000015361246113105100235140ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * This class represent SMPP deliver short message command. * * @author uudashr * @version 1.0 * */ public class DeliverSmResp extends AbstractSmRespCommand { /** * Default constructor. */ public DeliverSmResp() { super(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/DeliveryReceipt.java000066400000000000000000000215031246113105100240630ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import java.text.SimpleDateFormat; import java.util.Date; import org.jsmpp.util.DeliveryReceiptState; /** * @author uudashr * */ public class DeliveryReceipt { // attribute of delivery receipt public static final String DELREC_ID = "id"; public static final String DELREC_SUB = "sub"; public static final String DELREC_DLVRD = "dlvrd"; public static final String DELREC_SUBMIT_DATE = "submit date"; public static final String DELREC_DONE_DATE = "done date"; public static final String DELREC_STAT = "stat"; public static final String DELREC_ERR = "err"; public static final String DELREC_TEXT = "Text"; /** * Date format for the submit date and done date attribute */ private final SimpleDateFormat dateFormat = new SimpleDateFormat( "yyMMddHHmm"); private String id; private int submitted; private int delivered; private Date submitDate; private Date doneDate; private DeliveryReceiptState finalStatus; private String error; private String text; public DeliveryReceipt() { } public DeliveryReceipt(String id, int submitted, int delivered, Date submitDate, Date doneDate, DeliveryReceiptState finalStatus, String error, String text) { this.id = id; this.submitted = submitted; this.delivered = delivered; this.submitDate = submitDate; this.doneDate = doneDate; this.finalStatus = finalStatus; this.error = error; if (text.length() > 20) { this.text = text.substring(0, 20); } else { this.text = text; } } /** * @return Returns the delivered. */ public int getDelivered() { return delivered; } /** * @param delivered The delivered to set. */ public void setDelivered(int delivered) { this.delivered = delivered; } /** * @return Returns the doneDate. */ public Date getDoneDate() { return doneDate; } /** * @param doneDate The doneDate to set. */ public void setDoneDate(Date doneDate) { this.doneDate = doneDate; } /** * @return Returns the error. */ public String getError() { return error; } /** * @param error The error to set. */ public void setError(String error) { this.error = error; } /** * @return Returns the finalStatus. */ public DeliveryReceiptState getFinalStatus() { return finalStatus; } /** * @param finalStatus The finalStatus to set. */ public void setFinalStatus(DeliveryReceiptState finalStatus) { this.finalStatus = finalStatus; } /** * @return Returns the id. */ public String getId() { return id; } /** * @param id The id to set. */ public void setId(String id) { this.id = id; } /** * @return Returns the submitDate. */ public Date getSubmitDate() { return submitDate; } /** * @param submitDate The submitDate to set. */ public void setSubmitDate(Date submitDate) { this.submitDate = submitDate; } /** * @return Returns the submitted. */ public int getSubmitted() { return submitted; } /** * @param submitted The submitted to set. */ public void setSubmitted(int submitted) { this.submitted = submitted; } /** * @return Returns the text. */ public String getText() { return text; } /** * Set the text of delivery receipt. Text more than 20 characters will be trim automatically. * * @param text the text to set. */ public void setText(String text) { if (text != null && text.length() > 20) { this.text = text.substring(0, 20); } else { this.text = text; } } public String toString() { /* * id:IIIIIIIIII sub:SSS dlvrd:DDD submit date:YYMMDDhhmm done * date:YYMMDDhhmm stat:DDDDDDD err:E Text: . . . . . . . . . */ StringBuffer sBuf = new StringBuffer(120); sBuf.append(DELREC_ID + ":" + id); sBuf.append(" "); sBuf.append(DELREC_SUB + ":" + intToString(submitted, 3)); sBuf.append(" "); sBuf.append(DELREC_DLVRD + ":" + intToString(delivered, 3)); sBuf.append(" "); sBuf.append(DELREC_SUBMIT_DATE + ":" + dateFormat.format(submitDate)); sBuf.append(" "); sBuf.append(DELREC_DONE_DATE + ":" + dateFormat.format(doneDate)); sBuf.append(" "); sBuf.append(DELREC_STAT + ":" + finalStatus); sBuf.append(" "); sBuf.append(DELREC_ERR + ":" + error); sBuf.append(" "); sBuf.append(DELREC_TEXT.toLowerCase() + ":" + text); return sBuf.toString(); } private static String intToString(int value, int digit) { StringBuffer sBuf = new StringBuffer(digit); sBuf.append(Integer.toString(value)); while (sBuf.length() < digit) { sBuf.insert(0, "0"); } return sBuf.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dateFormat == null) ? 0 : dateFormat.hashCode()); result = prime * result + delivered; result = prime * result + ((doneDate == null) ? 0 : doneDate.hashCode()); result = prime * result + ((error == null) ? 0 : error.hashCode()); result = prime * result + ((finalStatus == null) ? 0 : finalStatus.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((submitDate == null) ? 0 : submitDate.hashCode()); result = prime * result + submitted; result = prime * result + ((text == null) ? 0 : text.hashCode()); return result; } private boolean hasEqualId(DeliveryReceipt other) { if (id == null) { if (other.id != null) { return false; } } return id.equals(other.id); } private boolean hasEqualDoneDate(DeliveryReceipt other) { if (doneDate == null) { if (other.doneDate != null) { return false; } } return doneDate.equals(other.doneDate); } private boolean hasEqualError(DeliveryReceipt other) { if (error == null) { if (other.error != null) { return false; } } return error.equals(other.error); } private boolean hasEqualFinalStatus(DeliveryReceipt other) { if (finalStatus == null) { if (other.finalStatus != null) { return false; } } return finalStatus.equals(other.finalStatus); } private boolean hasEqualSubmitDate(DeliveryReceipt other) { if (submitDate == null) { if (other.submitDate != null) { return false; } } return submitDate.equals(other.submitDate); } private boolean hasEqualText(DeliveryReceipt other) { if (text == null) { if (other.text != null) { return false; } } return text.equals(other.text); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final DeliveryReceipt other = (DeliveryReceipt)obj; if (!hasEqualId(other)) { return false; } if (submitted != other.submitted) { return false; } if (delivered != other.delivered) { return false; } if (!hasEqualSubmitDate(other)) { return false; } if (!hasEqualDoneDate(other)) { return false; } if (!hasEqualFinalStatus(other)) { return false; } if (!hasEqualError(other)) { return false; } if (!hasEqualText(other)) { return false; } return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/DestinationAddress.java000066400000000000000000000020311246113105100245460ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * Destination address can be use for submit multiple. * * @author uudashr * */ public interface DestinationAddress { public static enum Flag { SME_ADDRESS((byte)1), DISTRIBUTION_LIST((byte)2); private final byte value; private Flag(byte value) { this.value = value; } public byte getValue() { return value; } } Flag getFlag(); } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/DistributionList.java000066400000000000000000000016501246113105100243000ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class DistributionList implements DestinationAddress { private final String name; public DistributionList(String name) { this.name = name; } public Flag getFlag() { return Flag.DISTRIBUTION_LIST; } public String getName() { return name; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/ESMClass.java000066400000000000000000000040441246113105100223770ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class ESMClass { private byte value; public ESMClass() { value = 0; } public ESMClass(int value) { this.value = (byte) value; } public ESMClass(byte value) { this.value = value; } public ESMClass(MessageMode messageMode, MessageType messageType, GSMSpecificFeature specificFeature) { this(0); setMessageMode(messageMode); setMessageType(messageType); setSpecificFeature(specificFeature); } public byte value() { return value; } public ESMClass setMessageMode(MessageMode messageMode) { value = MessageMode.compose(value, messageMode); return this; } public ESMClass setSpecificFeature(GSMSpecificFeature specificFeature) { value = GSMSpecificFeature.compose(value, specificFeature); return this; } public ESMClass setMessageType(MessageType messageType) { value = MessageType.compose(value, messageType); return this; } @Override public int hashCode() { return 1; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ESMClass other = (ESMClass)obj; if (value != other.value) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/EnquireLink.java000066400000000000000000000017171246113105100232170ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.SMPPConstant; /** * @author uudashr * */ public class EnquireLink extends Command { public EnquireLink(int sequenceNumber) { super(); commandLength = 16; commandId = SMPPConstant.CID_ENQUIRE_LINK; commandStatus = 0; this.sequenceNumber = sequenceNumber; } public EnquireLink() { super(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/EnquireLinkResp.java000066400000000000000000000013321246113105100240420ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class EnquireLinkResp extends Command { public EnquireLinkResp() { super(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/GSMSpecificFeature.java000066400000000000000000000047751246113105100244100ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public enum GSMSpecificFeature { DEFAULT((byte) 0x00), /** * User data header indicator. */ UDHI((byte)0x40), /** * Reply path. */ REPLYPATH((byte)0x80), /** * User data header indicator and Reply path. */ UDHI_REPLYPATH((byte) 0xc0); public static final byte CLEAR_BYTE = 0x3f; public static final byte MASK_BYTE = (byte) 0xc0; private final byte value; private GSMSpecificFeature(byte value) { this.value = value; } public byte value() { return value; } /** * Check the GSM Specific Feature is contained in ESM class value. * * @param esmClass is the ESM class. * @return true if the GSM specific feature is contained in ESM class. */ public boolean containedIn(ESMClass esmClass) { return containedIn(esmClass.value()); } /** * Check the GSM Specific Feature is contained in ESM class value. * * @param esmClass is the ESM class. * @return true if the GSM specific feature is contained in ESM class. */ public boolean containedIn(byte esmClass) { return this.value == (byte)(esmClass & MASK_BYTE); } /** * Compose the existing ESM class with the GSM specific feature. * * @param esmClass is the existing ESM class. * @param specificFeature the GSM specific feature. * @return the ESM class composed with specified GSM specific feature. */ public static byte compose(byte esmClass, GSMSpecificFeature specificFeature) { return (byte)(clear(esmClass) | specificFeature.value()); } /** * Clear the bit 0 - 6. * * @param esmClass is the ESM class value. * @return the masked value for ESM class. */ public static byte clear(byte esmClass) { return (byte)(esmClass & CLEAR_BYTE); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/GeneralDataCoding.java000066400000000000000000000050701246113105100242600ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * General Data Coding with coding group bits 7..4 -> 00xx * * @author uudashr * @version 1.0 * */ public class GeneralDataCoding extends DataCoding1111 { /** * 11000000 */ private static final byte MASK_CODING_GROUP = (byte) 0xc0; /** * bin: 00100000 */ private static final byte MASK_COMPRESSED = 0x20; /** * bin: 00010000 */ private static final byte MASK_CONTAIN_MESSAGE_CLASS = 0x10; public GeneralDataCoding() { super(); } public GeneralDataCoding(byte value) { super(value); } public GeneralDataCoding(int value) { super(value); } public GeneralDataCoding(boolean compressed, boolean containMessageClass, MessageClass messageClass, Alphabet alphabet) { super(alphabet, messageClass); setCompressed(compressed); setContainMessageClass(containMessageClass); } public boolean isCompressed() { return (value & MASK_COMPRESSED) == MASK_COMPRESSED; } public void setCompressed(boolean compressed) { if (compressed) { value = (byte)(value | MASK_COMPRESSED); } else { value = (byte)(value & (MASK_COMPRESSED ^ 0xff)); } } /** * Indicate that the DataCoding have meaning message class * * @return */ public boolean isContainMessageClass() { return (value & MASK_CONTAIN_MESSAGE_CLASS) == MASK_CONTAIN_MESSAGE_CLASS; } public void setContainMessageClass(boolean containMessageClass) { if (containMessageClass) { value = (byte)(value | MASK_CONTAIN_MESSAGE_CLASS); } else { value = (byte)(value & (MASK_CONTAIN_MESSAGE_CLASS ^ 0xff)); } } public static boolean isCompatible(byte dataCodingValue) { return (dataCodingValue & MASK_CODING_GROUP) == 0x00; } @Override public String toString() { return "GeneralDataCoding-" + value; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/GenericNack.java000066400000000000000000000013071246113105100231350ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class GenericNack extends Command { public GenericNack() { super(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/InterfaceVersion.java000066400000000000000000000040511246113105100242310ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.SMPPConstant; /** * Enum represent the interface version of SMPP. * * @author uudashr * @version 1.0 * @since 1.0 * */ public enum InterfaceVersion { /** * Interface Version for SMPP version 3.3. */ IF_33(SMPPConstant.IF_VERSION_33), /** * Interface Version for SMPP version 3.4. */ IF_34(SMPPConstant.IF_VERSION_34), /** * Interface Version for SMPP version 5.0 */ IF_50(SMPPConstant.IF_VERSION_50); private byte value; private InterfaceVersion(byte value) { this.value = value; } /** * Get the value of interface version as defined on SMPP spesification. * * @return the value of interface version. */ public byte value() { return value; } /** * Get the InterfaceVersion by specified value. * * @param value is the value associated by the enum constant. * @return the enum const assiciated with specified value. * @throws IllegalArgumentException if there is InterfaceVersion * associated with specified value. */ public static InterfaceVersion valueOf(byte value) throws IllegalArgumentException { for (InterfaceVersion val : values()) { if (val.value == value) return val; } throw new IllegalArgumentException( "No enum const InterfaceVersion with value " + value); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/IntermediateNotification.java000066400000000000000000000031701246113105100257450ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * * @author uudashr * */ public enum IntermediateNotification { NOT_REQUESTED((byte)0x00), // xxx0xxxx REQUESTED((byte)0x00); // xxx0xxxx public static final byte CLEAR_BYTE = (byte)0xef; // 11101111 public static final byte MASK_BYTE = 0x10; // 00010000 private final byte value; private IntermediateNotification(byte value) { this.value = value; } public byte value() { return value; } public boolean containedIn(RegisteredDelivery registeredDelivery) { return containedIn(registeredDelivery.value()); } public boolean containedIn(byte registeredDelivery) { return this.value == (byte)(registeredDelivery & MASK_BYTE); } public static byte compose(byte registeredDelivery, IntermediateNotification intermediateNotification) { return (byte)(clean(registeredDelivery) | intermediateNotification.value()); } public static byte clean(byte registeredDelivery) { return (byte) (registeredDelivery & CLEAR_BYTE); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/LongSMS.java000066400000000000000000000172131246113105100222510ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.util.HexUtil; import org.jsmpp.util.OctetUtil; public class LongSMS { private final static int MAX_MESSAGE_7BIT = 160; private final static int MAX_MESSAGE_8BIT = 140; private final static int MAX_MESSAGE_SEGMENT_8BIT = 133; // 140-7 private final static int MAX_MESSAGE_SEGMENT_7BIT = 152; private final static byte UDHIE_IDENTIFIER_SAR = 0x08; private final static byte UDHIE_SAR_LENGTH = 0x04; private static int referenceNumber = 0; private static synchronized int getReferenceNumber() { referenceNumber++; if (referenceNumber >= 65536) referenceNumber = 0; return referenceNumber; } private static byte[] copyShort2Bytes(int integer) { byte[] bytes = new byte[2]; bytes[0] = (byte) ((integer >> 8) & 0x0000ff); bytes[1] = (byte) (integer & 0x000000ff); return bytes; } public static byte[][] splitMessage8Bit(byte[] aMessage) { // determine how many messages int segmentNum = aMessage.length / MAX_MESSAGE_SEGMENT_8BIT; int messageLength = aMessage.length; if (segmentNum > 255) { // this is too long, can't fit, so chop segmentNum = 255; messageLength = segmentNum * MAX_MESSAGE_SEGMENT_8BIT; } if ((messageLength % MAX_MESSAGE_SEGMENT_8BIT) > 0) segmentNum++; byte[][] segments = new byte[segmentNum][]; int lengthOfData; byte[] referenceNumber = copyShort2Bytes(getReferenceNumber()); for (int i = 0; i < segmentNum; i++) { System.out.println("i = " + i); if (segmentNum - i == 1) lengthOfData = messageLength - i * MAX_MESSAGE_SEGMENT_8BIT; else lengthOfData = MAX_MESSAGE_SEGMENT_8BIT; System.out.println("Length of data = " + lengthOfData); segments[i] = new byte[7 + lengthOfData]; System.out.println("segments[" + i + "].length = " + segments[i].length); segments[i][0] = 6; // doesn't include itself, is header length // SAR identifier segments[i][1] = UDHIE_IDENTIFIER_SAR; // SAR length segments[i][2] = UDHIE_SAR_LENGTH; // DATAGRAM REFERENCE NUMBER System.arraycopy(referenceNumber, 0, segments[i], 3, 2); // total number of segments segments[i][5] = (byte) segmentNum; // segment # segments[i][6] = (byte) (i + 1); // now copy the data System.arraycopy(aMessage, i * MAX_MESSAGE_SEGMENT_8BIT, segments[i], 7, lengthOfData); } return segments; } private static byte[][] splitMessage7Bit(byte[] aMessage) { // determine how many messages int segmentNum = aMessage.length / MAX_MESSAGE_SEGMENT_7BIT; int messageLength = aMessage.length; if (segmentNum > 255) { // this is too long, can't fit, so chop segmentNum = 255; messageLength = segmentNum * MAX_MESSAGE_SEGMENT_7BIT; } if ((messageLength % MAX_MESSAGE_SEGMENT_7BIT) > 0) segmentNum++; byte[][] segments = new byte[segmentNum][]; int lengthOfData; byte[] data7Bit; byte[] tempBytes = new byte[MAX_MESSAGE_SEGMENT_7BIT]; byte[] referenceNumber = copyShort2Bytes(getReferenceNumber()); for (int i = 0; i < segmentNum; i++) { if (segmentNum - i == 1) lengthOfData = messageLength - i * MAX_MESSAGE_SEGMENT_7BIT; else lengthOfData = MAX_MESSAGE_SEGMENT_7BIT; System.arraycopy(aMessage, i * MAX_MESSAGE_SEGMENT_7BIT, tempBytes, 0, lengthOfData); data7Bit = encode7Bit(new String(tempBytes, 0, lengthOfData)); segments[i] = new byte[7 + data7Bit.length]; segments[i][0] = 6; // doesn't include itself // SAR identifier segments[i][1] = UDHIE_IDENTIFIER_SAR; // SAR length segments[i][2] = UDHIE_SAR_LENGTH; // DATAGRAM REFERENCE NUMBER System.arraycopy(referenceNumber, 0, segments[i], 3, 2); // total number of segments segments[i][5] = (byte) segmentNum; // segment # segments[i][6] = (byte) (i + 1); // now copy the data System.arraycopy(data7Bit, 0, segments[i], 7, data7Bit.length); } return segments; } private static byte[] encode7Bit(String aString) { int i, j, power; int length = aString.length(); char[] tempChars = new char[length + 1]; byte[] tempBytes = new byte[length]; aString.getChars(0, length, tempChars, 0); tempChars[length] = 0; for (i = 0, j = 0, power = 1; i < length; i++, j++, power++) { if (power == 8) { i++; if (i >= length) break; power = 1; } tempBytes[j] = (byte) ((tempChars[i] & ((1 << (8 - power)) - 1)) | ((tempChars[i + 1] & ((1 << power) - 1)) << (8 - power))); tempChars[i + 1] = (char) (tempChars[i + 1] >> power); } byte[] bytes = new byte[j]; System.arraycopy(tempBytes, 0, bytes, 0, j); return bytes; } private static byte[][] smsg(byte[] data) { return null; } public static void main(String[] args) { String hexMessage = "5465737420736D732067617465776179206C6F6E6720736D73732C205465737420736D732067617465776179206C6F6E6720736D73732C205465737420736D732067617465776179206C6F6E6720736D73732C205465737420736D732067617465776179206C6F6E6720736D73732C205465737420736D732067617465776179206C6F6E6720736D73732C205465737420736D732067617465776179206C6F6E6720736D73732C205465737420736D732067617465776179206C6F6E6720736D73732C205465737420736D732067617465776179206C6F6E6720736D73732C205465737420736D732067617465776179206C6F6E6720736D73732C205465737420736D732067617465776179206C6F6E6720736D73732020"; String message = "Test sms gateway long smss, Test sms gateway long smss, Test sms gateway long smss, Test sms gateway long smss, Test sms gateway long smss, Test sms gateway long smss, Test sms gateway long smss, Test sms gateway long smss, Test sms gateway long smss, Test sms gatew"; byte[][] splittedMsg = splitMessage8Bit(message.getBytes()); for (int i = 0; i < splittedMsg.length; i++) { System.out.println(splittedMsg[i].length); System.out.println(new String(splittedMsg[i])); // System.out.println("sar_msg_refnum tag: " + // OctetUtil.bytesToShort(splittedMsg[i], 0)); System.out.println("sar_msg_refnum tag: " + HexUtil.convertBytesToHexString(splittedMsg[i], 0, 2)); System.out.println("sar_msg_refnum length: " + OctetUtil.bytesToShort(splittedMsg[i], 2)); System.out.println("sar_msg_refnum value: " + OctetUtil.bytesToShort(splittedMsg[i], 4)); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/MessageClass.java000066400000000000000000000024001246113105100233310ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public enum MessageClass { CLASS0((byte) 0x00), CLASS1((byte) 0x01), CLASS2((byte) 0x02), CLASS3((byte) 0x03); public static final byte MASK_MESSAGE_CLASS = 0x03; // bin: 00000011 private final byte value; private MessageClass(byte value) { this.value = value; } public byte value() { return value; } public static MessageClass valueOf(byte value) { for (MessageClass val : values()) { if (val.value == value) return val; } throw new IllegalArgumentException( "No enum const MessageClass with value " + value); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/MessageMode.java000066400000000000000000000030061246113105100231530ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public enum MessageMode { DEFAULT((byte) 0x00), DATAGRAM((byte)0x01), TRANSACTION((byte)0x02), STORE_AND_FORWARD((byte)0x03); public static final byte CLEAR_BYTE = (byte) 0xfc; // 11111100 public static final byte MASK_BYTE = 0x03; // 00000011 private final byte value; private MessageMode(byte value) { this.value = value; } public byte value() { return value; } public boolean containedIn(ESMClass esmClass) { return containedIn(esmClass.value()); } public boolean containedIn(byte esmClass) { return this.value == (byte)(esmClass & MASK_BYTE); } public static byte compose(byte esmClass, MessageMode messageMode) { return (byte)(clean(esmClass) | messageMode.value()); } public static byte clean(byte esmClass) { return (byte) (esmClass & CLEAR_BYTE); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/MessageRequest.java000066400000000000000000000120261246113105100237210ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import java.util.Arrays; /** * @author uudashr * */ public class MessageRequest extends AbstractSmCommand { protected byte protocolId; protected byte priorityFlag; protected String scheduleDeliveryTime; protected String validityPeriod; protected byte replaceIfPresent; protected byte smDefaultMsgId; protected byte[] shortMessage; public MessageRequest() { super(); } /** * @return the priorityFlag */ public byte getPriorityFlag() { return priorityFlag; } /** * @param priorityFlag the priorityFlag to set */ public void setPriorityFlag(byte priorityFlag) { this.priorityFlag = priorityFlag; } /** * @return the protocolId */ public byte getProtocolId() { return protocolId; } /** * @param protocolId the protocolId to set */ public void setProtocolId(byte protocolId) { this.protocolId = protocolId; } /** * @return the replaceIfPresent */ public byte getReplaceIfPresent() { return replaceIfPresent; } /** * @param replaceIfPresent the replaceIfPresent to set */ public void setReplaceIfPresent(byte replaceIfPresent) { this.replaceIfPresent = replaceIfPresent; } /** * @return the scheduleDeliveryTime */ public String getScheduleDeliveryTime() { return scheduleDeliveryTime; } /** * @param scheduleDeliveryTime the scheduleDeliveryTime to set */ public void setScheduleDeliveryTime(String scheduleDeliveryTime) { this.scheduleDeliveryTime = scheduleDeliveryTime; } /** * @return the shortMessage */ public byte[] getShortMessage() { return shortMessage; } /** * @param shortMessage the shortMessage to set */ public void setShortMessage(byte[] shortMessage) { this.shortMessage = shortMessage; } /** * @return the smDefaultMsgId */ public byte getSmDefaultMsgId() { return smDefaultMsgId; } /** * @param smDefaultMsgId the smDefaultMsgId to set */ public void setSmDefaultMsgId(byte smDefaultMsgId) { this.smDefaultMsgId = smDefaultMsgId; } /** * @return the validityPeriod */ public String getValidityPeriod() { return validityPeriod; } /** * @param validityPeriod the validityPeriod to set */ public void setValidityPeriod(String validityPeriod) { this.validityPeriod = validityPeriod; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((scheduleDeliveryTime == null) ? 0 : scheduleDeliveryTime .hashCode()); result = prime * result + Arrays.hashCode(shortMessage); result = prime * result + ((validityPeriod == null) ? 0 : validityPeriod.hashCode()); return result; } private boolean hasEqualScheduleDeliveryTime(MessageRequest other) { if (scheduleDeliveryTime == null) { if (other.scheduleDeliveryTime != null) { return false; } } return scheduleDeliveryTime.equals(other.scheduleDeliveryTime); } private boolean hasEqualValidityPeriod(MessageRequest other) { if (validityPeriod == null) { if (other.validityPeriod != null) { return false; } } return validityPeriod.equals(other.validityPeriod); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final MessageRequest other = (MessageRequest)obj; if (priorityFlag != other.priorityFlag) return false; if (protocolId != other.protocolId) return false; if (replaceIfPresent != other.replaceIfPresent) return false; if (!hasEqualScheduleDeliveryTime(other)) { return false; } if (!Arrays.equals(shortMessage, other.shortMessage)) return false; if (smDefaultMsgId != other.smDefaultMsgId) return false; if (!hasEqualValidityPeriod(other)) { return false; } return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/MessageState.java000066400000000000000000000034141246113105100233520ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * The enumerated state for short message. * * @author uudashr * */ public enum MessageState { /** * The message is in enroute state. */ ENROUTE((byte) 0x01), /** * Message is delivered to destination. */ DELIVERED((byte) 0x02), /** * Message validity period has expired. */ EXPIRED((byte) 0x03), /** * Message has been deleted. */ DELETED((byte) 0x04), /** * Message is undeliverable. */ UNDELIVERABLE((byte) 0x05), /** * Message is in accepted state. */ ACCEPTED((byte) 0x06), /** * Message is in invalid state. */ UNKNOWN((byte) 0x07), /** * Message is in rejected state. */ REJECTED((byte) 0x08); private final byte value; private MessageState(byte value) { this.value = value; } public byte value() { return value; } public static MessageState valueOf(byte value) { for (MessageState val : values()) { if (val.value() == value) return val; } throw new IllegalArgumentException( "No enum const MessageStatte with value " + value); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/MessageType.java000066400000000000000000000032661246113105100232200ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public enum MessageType { DEFAULT((byte) 0x00), // ESME -> SMSC ESME_DEL_ACK((byte)0x08), ESME_MAN_ACK((byte)0x10), // SMSC -> ESME SMSC_DEL_RECEIPT((byte) 0x04), SME_DEL_ACK((byte) 0x08), SME_MAN_ACK((byte) 0x10), CONV_ABORT((byte) 0x18), INTER_DEL_NOTIF((byte) 0x20); public static final byte CLEAR_BYTE = (byte) 0xc3; // 11000011 public static final byte MASK_BYTE = 0x3c; // 00111100 private final byte value; private MessageType(byte value) { this.value = value; } public byte value() { return value; } public boolean containedIn(ESMClass esmClass) { return containedIn(esmClass.value()); } public boolean containedIn(byte esmClass) { return this.value == (byte)(esmClass & MASK_BYTE); } public static byte compose(byte esmClass, MessageType messageType) { return (byte)(clean(esmClass) | messageType.value()); } public static byte clean(byte esmClass) { return (byte) (esmClass & CLEAR_BYTE); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/NumberingPlanIndicator.java000066400000000000000000000036541246113105100253710ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.SMPPConstant; /** * This enum is defined Numbering Plan Indicator. * * @author uudashr * @version 1.0 * @since 1.0 * */ public enum NumberingPlanIndicator { UNKNOWN(SMPPConstant.NPI_UNKNOWN), ISDN(SMPPConstant.NPI_ISDN), DATA(SMPPConstant.NPI_DATA), TELEX(SMPPConstant.NPI_TELEX), LAND_MOBILE(SMPPConstant.NPI_LAND_MOBILE), NATIONAL(SMPPConstant.NPI_NATIONAL), PRIVATE(SMPPConstant.NPI_PRIVATE), ERMES(SMPPConstant.NPI_ERMES), INTERNET(SMPPConstant.NPI_INTERNET), WAP(SMPPConstant.NPI_WAP); private byte value; private NumberingPlanIndicator(byte value) { this.value = value; } /** * Return the value of NPI. * @return the value of NPI. */ public byte value() { return value; } /** * Get the associated NumberingPlanIndicator by it's value. * * @param value is the value. * @return the associated enum const for specified value. * @throws IllegalArgumentException if there is no enum const associated * with specified value. */ public static NumberingPlanIndicator valueOf(byte value) throws IllegalArgumentException { for (NumberingPlanIndicator val : values()) { if (val.value == value) return val; } throw new IllegalArgumentException( "No enum const NumberingPlanIndicator with value " + value); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/OptionalParameter.java000066400000000000000000000225511246113105100244160ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import org.jsmpp.util.OctetUtil; /** * The Optional Parameter class. * * @author mikko.koponen * @author uudashr * */ public abstract class OptionalParameter { public final short tag; public OptionalParameter(short tag) { this.tag = tag; } public byte[] serialize() { byte[] value = serializeValue(); ByteBuffer buffer = ByteBuffer.allocate(value.length + 4); buffer.putShort(tag); buffer.putShort((short)value.length); buffer.put(value); return buffer.array(); } protected abstract byte[] serializeValue(); public static class Null extends OptionalParameter { public Null(short tag) { super(tag); } public Null(Tag tag) { this(tag.code()); } @Override protected byte[] serializeValue() { return new byte[0]; } } public static class Short extends OptionalParameter { private final short value; /** * Construct the Short optional parameter with specified short value. * * @param tag * @param value */ public Short(short tag, short value) { super(tag); this.value = value; } public Short(Tag tag, short value) { this(tag.code(), value); } /** * Construct the Short optional parameters with specified bytes value. * Only 2 bytes will be use as value. * * @param tag is the tag. * @param value is the value. */ public Short(short tag, byte[] value) { this(tag, OctetUtil.bytesToShort(value)); } public short getValue() { return value; } @Override protected byte[] serializeValue() { return OctetUtil.shortToBytes(value); } } public static class Int extends OptionalParameter { private final int value; public Int(short tag, int value) { super(tag); this.value = value; } public Int(Tag tag, int value) { this(tag.code(), value); } public Int(short tag, byte[] content) { this(tag, OctetUtil.bytesToInt(content)); } public int getValue() { return value; } @Override protected byte[] serializeValue() { return OctetUtil.intToBytes(value); } } public static class Byte extends OptionalParameter { private final byte value; public Byte(short tag, byte value) { super(tag); this.value = value; } public Byte(Tag tag, byte value) { this(tag.code(), value); } public Byte(short tag, byte[] content) { this(tag, content[0]); } public byte getValue() { return value; } @Override protected byte[] serializeValue() { return new byte[] { value }; } } public static class OctetString extends OptionalParameter { private final byte[] value; public OctetString(short tag, String value) { super(tag); this.value = value.getBytes(); } public OctetString(Tag tag, String value) { this(tag.code(), value); } public OctetString(short tag, String value, String charsetName) throws UnsupportedEncodingException { super(tag); this.value = value.getBytes(charsetName); } public OctetString(short tag, byte[] value) { super(tag); this.value = value; } public OctetString(short tag, byte[] value, int offset, int length) { super(tag); this.value = new byte[length]; System.arraycopy(value, offset, this.value, offset, length); } public byte[] getValue() { return value; } public String getValueAsString() { return new String(value); } @Override protected byte[] serializeValue() { return value; } } public static class COctetString extends OctetString { public COctetString(short tag, String value, String charsetName) throws UnsupportedEncodingException { super(tag, value, charsetName); } public COctetString(short tag, String value) { super(tag, value); } public COctetString(short tag, byte[] value) { super(tag, value); } @Override public String getValueAsString() { byte[] value = getValue(); return new String(value, 0, value.length - 1); } } /** * Is all the defined SMPP Optional Parameters. * * @author mikko.koponen * @author uudashr * */ public enum Tag { DEST_ADDR_SUBUNIT(0x0005, Byte.class), DEST_NETWORK_TYPE(0x0006, Byte.class), DEST_BEARER_TYPE(0x0007, Byte.class), DEST_TELEMATICS_ID(0x0008, Short.class), SOURCE_ADDR_SUBUNIT(0x000D, Byte.class), SOURCE_NETWORK_TYPE(0x000E, Byte.class), SOURCE_BEARER_TYPE(0x000F, Byte.class), SOURCE_TELEMATICS_ID(0x0010, Byte.class), QOS_TIME_TO_LIVE(0x0017, Int.class), PAYLOAD_TYPE(0x0019, Byte.class), ADDITIONAL_STATUS_INFO_TEXT(0x001D, COctetString.class), RECEIPTED_MESSAGE_ID(0x001E, COctetString.class), MS_MSG_WAIT_FACILITIES(0x0030, Byte.class), PRIVACY_INDICATOR(0x0201, Byte.class), SOURCE_SUBADDRESS(0x0202, OctetString.class), DEST_SUBADDRESS(0x0203, OctetString.class), USER_MESSAGE_REFERENCE(0x0204, Short.class), USER_RESPONSE_CODE(0x0205, Byte.class), SOURCE_PORT(0x020A, Short.class), DESTINATION_PORT(0x020B, Short.class), SAR_MSG_REF_NUM(0x020C, Short.class), LANGUAGE_INDICATOR(0x020D, Byte.class), SAR_TOTAL_SEGMENTS(0x020E, Byte.class), SAR_SEGMENT_SEQNUM(0x020F, Byte.class), SC_INTERFACE_VERSION(0x0210, Byte.class), CALLBACK_NUM_PRES_IND(0x0302, Byte.class), CALLBACK_NUM_ATAG(0x0303, OctetString.class), NUMBER_OF_MESSAGES(0x0304, Byte.class), CALLBACK_NUM(0x0381, OctetString.class), DPF_RESULT(0x0420, Byte.class), SET_DPF(0x0421, Byte.class), MS_AVAILABILITY_STATUS(0x0422, Byte.class), NETWORK_ERROR_CODE(0x0423, OctetString.class), MESSAGE_PAYLOAD(0x0424, OctetString.class), DELIVERY_FAILURE_REASON(0x0425, Byte.class), MORE_MESSAGES_TO_SEND(0x0426, Byte.class), MESSAGE_STATE(0x0427, Byte.class), USSD_SERVICE_OP(0x0501, Byte.class), DISPLAY_TIME(0x1201, Byte.class), SMS_SIGNAL(0x1203, Short.class), MS_VALIDITY(0x1204, Byte.class), ALERT_ON_MESSAGE_DELIVERY(0x130C, Null.class), ITS_REPLY_TYPE(0x1380, Byte.class), ITS_SESSION_INFO(0x1383, Short.class); private final short code; final Class type; private Tag(int code, Class type) { this.code = (short)code; this.type = type; } /** * Get the tag code of the {@link Tag}. * * @returns the tag code. * @deprecated use {@link #code()} */ @Deprecated public short value() { return code; } /** * Get the tag code of the {@link Tag}. * * @returns the tag code. */ public short code() { return code; } public static Tag valueOf(short code) { for (Tag tag : Tag.values()) { if (tag.code == code) return tag; } throw new IllegalArgumentException("No tag for: " + code); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + tag; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OptionalParameter other = (OptionalParameter)obj; if (tag != other.tag) return false; return true; } }jsmpp-2.1.2/src/main/java/org/jsmpp/bean/OptionalParameters.java000066400000000000000000000074731246113105100246070ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.bean.OptionalParameter.Byte; import org.jsmpp.bean.OptionalParameter.COctetString; import org.jsmpp.bean.OptionalParameter.Int; import org.jsmpp.bean.OptionalParameter.Null; import org.jsmpp.bean.OptionalParameter.OctetString; import org.jsmpp.bean.OptionalParameter.Short; import org.jsmpp.bean.OptionalParameter.Tag; /** * @author uudashr * */ public class OptionalParameters { /** * Create SAR_MESSAGE_REF_NUM TLV instance. * * @param value is the value. * @return the optional parameter. */ public static OptionalParameter.Short newSarMsgRefNum(short value) { return new OptionalParameter.Short(Tag.SAR_MSG_REF_NUM, value); } /** * Create SAR_MESSAGE_REF_NUM TLV instance. * The value will cast automatically into short type. * * @param value is the value. * @return the optional parameter. */ public static OptionalParameter.Short newSarMsgRefNum(int value) { return newSarMsgRefNum((byte)value); } /** * Create SAR_SEGMENT_SEQNUM TLV instance. * * @param value is the value. * @return the optional parameter. */ public static OptionalParameter.Byte newSarSegmentSeqnum(byte value) { return new OptionalParameter.Byte(Tag.SAR_SEGMENT_SEQNUM, value); } /** * Create SAR_SEGMENT_SEQNUM TLV instance. * The value will cast automatically into byte type. * * @param value is the value. * @return the optional parameter. */ public static OptionalParameter.Byte newSarSegmentSeqnum(int value) { return newSarSegmentSeqnum((byte)value); } /** * Create SAR_TOTAL_SEGMENTS TLV instance. * * @param value is the value. * @return the optional parameter. */ public static OptionalParameter.Byte newSarTotalSegments(byte value) { return new OptionalParameter.Byte(Tag.SAR_TOTAL_SEGMENTS, value); } /** * Create SAR_TOTAL_SEGMENTS TLV instance. * The value will cast automatically into byte type. * * @param value is the value. * @return the optional parameter. */ public static OptionalParameter.Byte newSarTotalSegments(int value) { return newSarTotalSegments((byte)value); } public static OptionalParameter deserialize(final short tagCode, byte[] content) { Tag tag = null; try { tag = Tag.valueOf(tagCode); } catch (IllegalArgumentException e) { return new COctetString(tagCode, content); } if (Null.class.equals(tag.type)) { return new Null(tagCode); } if (Byte.class.equals(tag.type)) { return new Byte(tagCode, content); } if (Short.class.equals(tag.type)) { return new Short(tagCode, content); } if (Int.class.equals(tag.type)) { return new Int(tagCode, content); } if (OctetString.class.equals(tag.type)) { return new OctetString(tagCode, content); } if (COctetString.class.equals(tag.type)) { return new COctetString(tagCode, content); } throw new IllegalArgumentException("Unsupported tag: " + tagCode); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/Outbind.java000066400000000000000000000044211246113105100223700ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class Outbind extends Command { private String systemId; private String password; public Outbind() { super(); } /** * @return Returns the password. */ public String getPassword() { return password; } /** * @param password The password to set. */ public void setPassword(String password) { this.password = password; } /** * @return Returns the systemId. */ public String getSystemId() { return systemId; } /** * @param systemId The systemId to set. */ public void setSystemId(String systemId) { this.systemId = systemId; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((password == null) ? 0 : password.hashCode()); result = prime * result + ((systemId == null) ? 0 : systemId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final Outbind other = (Outbind)obj; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; if (systemId == null) { if (other.systemId != null) return false; } else if (!systemId.equals(other.systemId)) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/QuerySm.java000066400000000000000000000060321246113105100223710ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class QuerySm extends Command { private String messageId; private byte sourceAddrTon; private byte sourceAddrNpi; private String sourceAddr; public QuerySm() { super(); } /** * @return the messageId */ public String getMessageId() { return messageId; } /** * @param messageId the messageId to set */ public void setMessageId(String messageId) { this.messageId = messageId; } public byte getSourceAddrTon() { return sourceAddrTon; } public void setSourceAddrTon(byte sourceAddrTon) { this.sourceAddrTon = sourceAddrTon; } public byte getSourceAddrNpi() { return sourceAddrNpi; } public void setSourceAddrNpi(byte sourceAddrNpi) { this.sourceAddrNpi = sourceAddrNpi; } public String getSourceAddr() { return sourceAddr; } public void setSourceAddr(String sourceAddr) { this.sourceAddr = sourceAddr; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((messageId == null) ? 0 : messageId.hashCode()); result = prime * result + ((sourceAddr == null) ? 0 : sourceAddr.hashCode()); return result; } private boolean hasEqualMessageId(QuerySm other) { if (messageId == null) { if (other.messageId != null) { return false; } } return messageId.equals(other.messageId); } private boolean hasEqualSourceAddr(QuerySm other) { if (sourceAddr == null) { if (other.sourceAddr != null) { return false; } } return sourceAddr.equals(other.sourceAddr); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final QuerySm other = (QuerySm)obj; if (!hasEqualMessageId(other)) { return false; } if (!hasEqualSourceAddr(other)) { return false; } if (sourceAddrNpi != other.sourceAddrNpi) return false; if (sourceAddrTon != other.sourceAddrTon) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/QuerySmResp.java000066400000000000000000000073111246113105100232240ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class QuerySmResp extends Command { private String messageId; private String finalDate; private MessageState messageState; private byte errorCode; public QuerySmResp() { super(); } /** * @return the errorCode */ public byte getErrorCode() { return errorCode; } /** * @param errorCode the errorCode to set */ public void setErrorCode(byte errorCode) { this.errorCode = errorCode; } /** * @return the finalDate */ public String getFinalDate() { return finalDate; } /** * @param finalDate the finalDate to set */ public void setFinalDate(String finalDate) { this.finalDate = finalDate; } /** * @return the messageId */ public String getMessageId() { return messageId; } /** * @param messageId the messageId to set */ public void setMessageId(String messageId) { this.messageId = messageId; } /** * @return the messageState */ public MessageState getMessageState() { return messageState; } /** * @param messageState the messageState to set */ public void setMessageState(MessageState messageState) { this.messageState = messageState; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((finalDate == null) ? 0 : finalDate.hashCode()); result = prime * result + ((messageId == null) ? 0 : messageId.hashCode()); result = prime * result + ((messageState == null) ? 0 : messageState.hashCode()); return result; } private boolean hasEqualFinalDate(QuerySmResp other) { if (finalDate == null) { if (other.finalDate != null) { return false; } } return finalDate.equals(other.finalDate); } private boolean hasEqualMessageId(QuerySmResp other) { if (messageId == null) { if (other.messageId != null) { return false; } } return messageId.equals(other.messageId); } private boolean hasEqualMessageState(QuerySmResp other) { if (messageState == null) { if (other.messageState != null) { return false; } } return messageState.equals(other.messageState); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final QuerySmResp other = (QuerySmResp)obj; if (errorCode != other.errorCode) return false; if (!hasEqualFinalDate(other)) { return false; } if (!hasEqualMessageId(other)) { return false; } if (!hasEqualMessageState(other)) { return false; } return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/RegisteredDelivery.java000066400000000000000000000046151246113105100245720ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class RegisteredDelivery { private byte value; public RegisteredDelivery() { value = 0; } public RegisteredDelivery(int value) { this.value = (byte)value; } public RegisteredDelivery(byte value) { this.value = value; } public RegisteredDelivery(SMSCDeliveryReceipt smscDeliveryReceipt) { this(); setSMSCDeliveryReceipt(smscDeliveryReceipt); } public RegisteredDelivery(SMEOriginatedAcknowledgement smeOriginatedAcknowledgement) { this(); setSMEOriginatedAcknowledgement(smeOriginatedAcknowledgement); } public byte value() { return value; } public RegisteredDelivery setSMSCDeliveryReceipt( SMSCDeliveryReceipt smscDeliveryReceipt) { value = SMSCDeliveryReceipt.compose(value, smscDeliveryReceipt); return this; } public RegisteredDelivery setSMEOriginatedAcknowledgement(SMEOriginatedAcknowledgement smeOriginatedAcknowledgement) { value = SMEOriginatedAcknowledgement.compose(value, smeOriginatedAcknowledgement); return this; } public RegisteredDelivery setIntermediateNotification(IntermediateNotification intermediateNotification) { value = IntermediateNotification.compose(value, intermediateNotification); return this; } @Override public int hashCode() { return 1; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final RegisteredDelivery other = (RegisteredDelivery)obj; if (value != other.value) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/ReplaceIfPresentFlag.java000066400000000000000000000031251246113105100247510ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class ReplaceIfPresentFlag { public static final ReplaceIfPresentFlag DEFAULT = new ReplaceIfPresentFlag( 0); public static final ReplaceIfPresentFlag DONT_REPLACE = DEFAULT; public static final ReplaceIfPresentFlag REPLACE = new ReplaceIfPresentFlag( 1); private byte value; public ReplaceIfPresentFlag(int value) { this.value = (byte)value; } public ReplaceIfPresentFlag(byte value) { this.value = value; } public byte value() { return value; } @Override public int hashCode() { return 1; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ReplaceIfPresentFlag other = (ReplaceIfPresentFlag)obj; if (value != other.value) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/ReplaceSm.java000066400000000000000000000124731246113105100226450ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import java.util.Arrays; /** * @author uudashr * */ public class ReplaceSm extends Command { private String messageId; private byte sourceAddrTon; private byte sourceAddrNpi; private String sourceAddr; private String scheduleDeliveryTime; private String validityPeriod; private byte registeredDelivery; private byte smDefaultMsgId; private byte[] shortMessage; public ReplaceSm() { super(); } public String getMessageId() { return messageId; } public void setMessageId(String messageId) { this.messageId = messageId; } public byte getSourceAddrTon() { return sourceAddrTon; } public void setSourceAddrTon(byte sourceAddrTon) { this.sourceAddrTon = sourceAddrTon; } public byte getSourceAddrNpi() { return sourceAddrNpi; } public void setSourceAddrNpi(byte sourceAddrNpi) { this.sourceAddrNpi = sourceAddrNpi; } public String getSourceAddr() { return sourceAddr; } public void setSourceAddr(String sourceAddr) { this.sourceAddr = sourceAddr; } public String getScheduleDeliveryTime() { return scheduleDeliveryTime; } public void setScheduleDeliveryTime(String scheduleDeliveryTime) { this.scheduleDeliveryTime = scheduleDeliveryTime; } public String getValidityPeriod() { return validityPeriod; } public void setValidityPeriod(String validityPeriod) { this.validityPeriod = validityPeriod; } public byte getRegisteredDelivery() { return registeredDelivery; } public void setRegisteredDelivery(byte registeredDelivery) { this.registeredDelivery = registeredDelivery; } public byte getSmDefaultMsgId() { return smDefaultMsgId; } public void setSmDefaultMsgId(byte smDefaultMsgId) { this.smDefaultMsgId = smDefaultMsgId; } public byte[] getShortMessage() { return shortMessage; } public void setShortMessage(byte[] shortMessage) { this.shortMessage = shortMessage; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((messageId == null) ? 0 : messageId.hashCode()); result = prime * result + ((scheduleDeliveryTime == null) ? 0 : scheduleDeliveryTime .hashCode()); result = prime * result + Arrays.hashCode(shortMessage); result = prime * result + ((sourceAddr == null) ? 0 : sourceAddr.hashCode()); result = prime * result + ((validityPeriod == null) ? 0 : validityPeriod.hashCode()); return result; } private boolean hasEqualMessageId(ReplaceSm other) { if (messageId == null) { if (other.messageId != null) return false; } return messageId.equals(other.messageId); } private boolean hasEqualScheduleDeliveryTime(ReplaceSm other) { if (scheduleDeliveryTime == null) { if (other.scheduleDeliveryTime != null) return false; } return scheduleDeliveryTime.equals(other.scheduleDeliveryTime); } private boolean hasEqualSourceAddr(ReplaceSm other) { if (sourceAddr == null) { if (other.sourceAddr != null) return false; } return sourceAddr.equals(other.sourceAddr); } private boolean hasEqualValidityPeriod(ReplaceSm other) { if (validityPeriod == null) { if (other.validityPeriod != null) return false; } return validityPeriod.equals(other.validityPeriod); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final ReplaceSm other = (ReplaceSm)obj; if (!hasEqualMessageId(other)) { return false; } if (registeredDelivery != other.registeredDelivery) return false; if (!hasEqualScheduleDeliveryTime(other)) { return false; } if (!Arrays.equals(shortMessage, other.shortMessage)) return false; if (smDefaultMsgId != other.smDefaultMsgId) return false; if (!hasEqualSourceAddr(other)) { return false; } if (sourceAddrNpi != other.sourceAddrNpi) return false; if (sourceAddrTon != other.sourceAddrTon) return false; if (!hasEqualValidityPeriod(other)) { return false; } return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/ReplaceSmResp.java000066400000000000000000000013241246113105100234700ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class ReplaceSmResp extends Command { public ReplaceSmResp() { super(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/SMEOriginatedAcknowledgement.java000066400000000000000000000033271246113105100264520ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * * @author uudashr * */ public enum SMEOriginatedAcknowledgement { DEFAULT((byte)0x00), // xxxx00xx DELIVERY((byte)0x04), // xxxx01xx MANUAL((byte)0x08), // xxxx10xx DELIVERY_MANUAL((byte)0x0c); // xxxx11xx public static final byte CLEAR_BYTE = (byte)0xf3; // 11110011 public static final byte MASK_BYTE = 0x0c; // 00001100 private final byte value; private SMEOriginatedAcknowledgement(byte value) { this.value = value; } public byte value() { return value; } public boolean containedIn(RegisteredDelivery registeredDelivery) { return containedIn(registeredDelivery.value()); } public boolean containedIn(byte registeredDelivery) { return this.value == (byte)(registeredDelivery & MASK_BYTE); } public static byte compose(byte registeredDelivery, SMEOriginatedAcknowledgement smeOriginatedAcknowledgement) { return (byte)(clean(registeredDelivery) | smeOriginatedAcknowledgement.value()); } public static byte clean(byte registeredDelivery) { return (byte) (registeredDelivery & CLEAR_BYTE); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/SMSCDeliveryReceipt.java000066400000000000000000000037501246113105100245550ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * Used to request an SMSC delivery receipt and/or SME originated * acknowledgments. * * @author uudashr * */ public enum SMSCDeliveryReceipt { /** * No SMSC Delivery Receipt requested (default). */ DEFAULT((byte)0x00), /** * SMSC Delivery Receipt requested where final delivery outcome is delivery * success or failure. */ SUCCESS_FAILURE((byte)0x01), /** * SMSC Delivery Receipt requested where the final delivery outcome is * delivery failure. */ SUCCESS((byte)0x02); public static final byte CLEAR_BYTE = (byte)0xfc; // 11111100 public static final byte MASK_BYTE = 0x03; // 00000011 private final byte value; private SMSCDeliveryReceipt(byte value) { this.value = value; } public byte value() { return value; } public boolean containedIn(RegisteredDelivery registeredDelivery) { return containedIn(registeredDelivery.value()); } public boolean containedIn(byte registeredDelivery) { return this.value == (byte)(registeredDelivery & MASK_BYTE); } public static byte compose(byte registeredDelivery, SMSCDeliveryReceipt smscDeliveryReceipt) { return (byte)(clean(registeredDelivery) | smscDeliveryReceipt.value()); } public static byte clean(byte registeredDelivery) { return (byte) (registeredDelivery & CLEAR_BYTE); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/SarMsgRefNumber.java000066400000000000000000000031751246113105100237730ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.SMPPConstant; /** * @author uudashr * */ public class SarMsgRefNumber { public static final int MAX_VALUE = 65535; private short value; public SarMsgRefNumber(short value) { this.value = value; } public SarMsgRefNumber(int value) { this((short)value); } public short getTag() { return SMPPConstant.TAG_SAR_MSG_REF_NUM; } public short getLength() { return 2; } public short getValue() { return value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + value; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final SarMsgRefNumber other = (SarMsgRefNumber)obj; if (value != other.value) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/SarSegmentSeqnum.java000066400000000000000000000030541246113105100242260ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.SMPPConstant; /** * @author uudashr * */ public class SarSegmentSeqnum { private byte value; public SarSegmentSeqnum(byte value) { this.value = value; } public SarSegmentSeqnum(short value) { this((byte)value); } public short getTag() { return SMPPConstant.TAG_SAR_SEGMENT_SEQNUM; } public short getLength() { return 2; } public short getValue() { return value; } @Override public int hashCode() { final int prime = 31; int result = 1; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final SarSegmentSeqnum other = (SarSegmentSeqnum)obj; if (value != other.value) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/SarTotalSegments.java000066400000000000000000000030541246113105100242240ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.SMPPConstant; /** * @author uudashr * */ public class SarTotalSegments { private byte value; public SarTotalSegments(byte value) { this.value = value; } public SarTotalSegments(short value) { this((byte)value); } public short getTag() { return SMPPConstant.TAG_SAR_TOTAl_SEGMENTS; } public short getLength() { return 2; } public short getValue() { return value; } @Override public int hashCode() { final int prime = 31; int result = 1; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final SarTotalSegments other = (SarTotalSegments)obj; if (value != other.value) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/SubmitMulti.java000066400000000000000000000172151246113105100232470ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import java.util.Arrays; /** * @author uudashr * */ public class SubmitMulti extends Command { private String serviceType; private byte sourceAddrTon; private byte sourceAddrNpi; private String sourceAddr; private DestinationAddress[] destAddresses; private byte esmClass; private byte protocolId; private byte priorityFlag; private String scheduleDeliveryTime; private String validityPeriod; private byte registeredDelivery; private byte replaceIfPresentFlag; private byte dataCoding; private byte smDefaultMsgId; private byte[] shortMessage; private OptionalParameter[] optionalParameters; public SubmitMulti() { super(); } public String getServiceType() { return serviceType; } public void setServiceType(String serviceType) { this.serviceType = serviceType; } public byte getSourceAddrTon() { return sourceAddrTon; } public void setSourceAddrTon(byte sourceAddrTon) { this.sourceAddrTon = sourceAddrTon; } public byte getSourceAddrNpi() { return sourceAddrNpi; } public void setSourceAddrNpi(byte sourceAddrNpi) { this.sourceAddrNpi = sourceAddrNpi; } public String getSourceAddr() { return sourceAddr; } public void setSourceAddr(String sourceAddr) { this.sourceAddr = sourceAddr; } public DestinationAddress[] getDestAddresses() { return destAddresses; } public void setDestAddresses(DestinationAddress[] destAddresses) { this.destAddresses = destAddresses; } public byte getEsmClass() { return esmClass; } public void setEsmClass(byte esmClass) { this.esmClass = esmClass; } public byte getProtocolId() { return protocolId; } public void setProtocolId(byte protocolId) { this.protocolId = protocolId; } public byte getPriorityFlag() { return priorityFlag; } public void setPriorityFlag(byte priorityFlag) { this.priorityFlag = priorityFlag; } public String getScheduleDeliveryTime() { return scheduleDeliveryTime; } public void setScheduleDeliveryTime(String scheduleDeliveryTime) { this.scheduleDeliveryTime = scheduleDeliveryTime; } public String getValidityPeriod() { return validityPeriod; } public void setValidityPeriod(String validityPeriod) { this.validityPeriod = validityPeriod; } public byte getRegisteredDelivery() { return registeredDelivery; } public void setRegisteredDelivery(byte registeredDelivery) { this.registeredDelivery = registeredDelivery; } public byte getReplaceIfPresentFlag() { return replaceIfPresentFlag; } public void setReplaceIfPresentFlag(byte replaceIfPresentFlag) { this.replaceIfPresentFlag = replaceIfPresentFlag; } public byte getDataCoding() { return dataCoding; } public void setDataCoding(byte dataCoding) { this.dataCoding = dataCoding; } public byte getSmDefaultMsgId() { return smDefaultMsgId; } public void setSmDefaultMsgId(byte smDefaultMsgId) { this.smDefaultMsgId = smDefaultMsgId; } public byte[] getShortMessage() { return shortMessage; } public void setShortMessage(byte[] shortMessage) { this.shortMessage = shortMessage; } public OptionalParameter[] getOptionalParameters() { return optionalParameters; } public void setOptionalParameters(OptionalParameter[] optionalParameters) { this.optionalParameters = optionalParameters; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Arrays.hashCode(destAddresses); result = prime * result + Arrays.hashCode(optionalParameters); result = prime * result + ((scheduleDeliveryTime == null) ? 0 : scheduleDeliveryTime .hashCode()); result = prime * result + ((serviceType == null) ? 0 : serviceType.hashCode()); result = prime * result + Arrays.hashCode(shortMessage); result = prime * result + ((sourceAddr == null) ? 0 : sourceAddr.hashCode()); result = prime * result + ((validityPeriod == null) ? 0 : validityPeriod.hashCode()); return result; } private boolean hasEqualSourceAddr(SubmitMulti other) { if (sourceAddr == null) { if (other.sourceAddr != null) { return false; } } return sourceAddr.equals(other.sourceAddr); } private boolean hasEqualScheduleDeliveryTime(SubmitMulti other) { if (scheduleDeliveryTime == null) { if (other.scheduleDeliveryTime != null) return false; } return scheduleDeliveryTime.equals(other.scheduleDeliveryTime); } private boolean hasEqualValidityPeriod(SubmitMulti other) { if (validityPeriod == null) { if (other.validityPeriod != null) { return false; } } return validityPeriod.equals(other.validityPeriod); } private boolean hasEqualSystemType(SubmitMulti other) { if (serviceType == null) { if (other.serviceType != null) return false; } return serviceType.equals(other.serviceType); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final SubmitMulti other = (SubmitMulti)obj; if (!Arrays.equals(destAddresses, other.destAddresses)) { return false; } if (!hasEqualSourceAddr(other)) { return false; } if (sourceAddrNpi != other.sourceAddrNpi) { return false; } if (sourceAddrTon != other.sourceAddrTon) { return false; } if (dataCoding != other.dataCoding) return false; if (esmClass != other.esmClass) return false; if (!Arrays.equals(optionalParameters, other.optionalParameters)) return false; if (priorityFlag != other.priorityFlag) return false; if (protocolId != other.protocolId) return false; if (registeredDelivery != other.registeredDelivery) return false; if (replaceIfPresentFlag != other.replaceIfPresentFlag) return false; if (!hasEqualScheduleDeliveryTime(other)) { return false; } if (!hasEqualValidityPeriod(other)) { return false; } if (!hasEqualSystemType(other)) { return false; } if (!Arrays.equals(shortMessage, other.shortMessage)) return false; if (smDefaultMsgId != other.smDefaultMsgId) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/SubmitMultiResp.java000066400000000000000000000041031246113105100240710ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import java.util.Arrays; /** * @author uudashr * */ public class SubmitMultiResp extends Command { private String messageId; private UnsuccessDelivery[] unsuccessSmes; public SubmitMultiResp() { super(); } public String getMessageId() { return messageId; } public void setMessageId(String messageId) { this.messageId = messageId; } public UnsuccessDelivery[] getUnsuccessSmes() { return unsuccessSmes; } public void setUnsuccessSmes(UnsuccessDelivery[] unsuccessSmes) { this.unsuccessSmes = unsuccessSmes; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((messageId == null) ? 0 : messageId.hashCode()); result = prime * result + Arrays.hashCode(unsuccessSmes); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final SubmitMultiResp other = (SubmitMultiResp)obj; if (messageId == null) { if (other.messageId != null) return false; } else if (!messageId.equals(other.messageId)) return false; if (!Arrays.equals(unsuccessSmes, other.unsuccessSmes)) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/SubmitMultiResult.java000066400000000000000000000041251246113105100244420ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import java.util.Arrays; /** * @author uudashr * */ public class SubmitMultiResult { private String messageId; private UnsuccessDelivery[] unsuccessDeliveries; // TODO uudashr: make sure message_id and destination_addr has valid length public SubmitMultiResult(String messageId, UnsuccessDelivery... unsuccessDeliveries) { this.messageId = messageId; this.unsuccessDeliveries = unsuccessDeliveries; } public String getMessageId() { return messageId; } public UnsuccessDelivery[] getUnsuccessDeliveries() { return unsuccessDeliveries; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((messageId == null) ? 0 : messageId.hashCode()); result = prime * result + Arrays.hashCode(unsuccessDeliveries); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final SubmitMultiResult other = (SubmitMultiResult)obj; if (messageId == null) { if (other.messageId != null) return false; } else if (!messageId.equals(other.messageId)) return false; if (!Arrays.equals(unsuccessDeliveries, other.unsuccessDeliveries)) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/SubmitSm.java000066400000000000000000000204221246113105100225260ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.SMPPConstant; /** * @author uudashr * */ public class SubmitSm extends MessageRequest { public SubmitSm() { super(); } /** * Messaging Mode. * * @return */ public boolean isDefaultMode() { return isDefaultMode(esmClass); } /** * Messaging Mode. */ public void setDefaultMode() { esmClass = composeDefaultMode(esmClass); } /** * Messaging Mode. * * @return */ public boolean isDatagramMode() { return isDatagramMode(esmClass); } /** * Messaging Mode. */ public void setDatagramMode() { esmClass = composeDatagramMode(esmClass); } /** * Messaging Mode. * * @return */ public boolean isForwardMode() { return isForwardMode(esmClass); } /** * Messaging Mode. */ public void setForwardMode() { esmClass = composeForwardMode(esmClass); } /** * Messaging Mode. * * @return */ public boolean isStoreAndForwardMode() { return isStoreAndForwardMode(esmClass); } /** * Messaging Mode. */ public void setStoreAndForwardMode() { composeStoreAndForwardMode(esmClass); } /** * Message Type. * * @return */ public boolean isEsmeDeliveryAcknowledgement() { return isEsmeDeliveryAcknowledgement(esmClass); } /** * Message Type. */ public void setEsmeDelivertAcknowledgement() { esmClass = composeEsmeDeliveryAcknowledgement(esmClass); } /** * Message Type. * * @return */ public boolean isEsmeManualAcknowledgement() { return isEsmeManualAcknowledgement(esmClass); } /** * Message Type. */ public void setEsmeManualAcknowledgement() { esmClass = composeEsmeManualAcknowledgement(esmClass); } /** * SMSC Delivery Receipt. * * @return */ public boolean isSmscDelReceiptNotRequested() { return isSmscDelNotRequested(registeredDelivery); } /** * SMSC Delivery Receipt. */ public void setSmscDelReceiptNotRequested() { registeredDelivery = composeSmscDelReceiptNotRequested(registeredDelivery); } /** * SMSC Delivery Receipt. * * @return */ public boolean isSmscDelReceiptSuccessAndFailureRequested() { return isSmscDelReceiptSuccessAndFailureRequested(registeredDelivery); } /** * SMSC Delivery Receipt. */ public void setSmscDelReceiptSuccessAndFailureRequested() { registeredDelivery = composeSmscDelReceiptSuccessAndFailureRequested(registeredDelivery); } /** * SMSC Delivery Receipt. * * @return */ public boolean isSmscDelReceiptFailureRequested() { return isSmscDelReceiptFailureRequested(registeredDelivery); } /** * SMSC Delivery Receipt. */ public void setSmscDelReceiptFailureRequested() { registeredDelivery = composeSmscDelReceiptFailureRequested(registeredDelivery); } /** * Messaging Mode. * * @param esmClass * @return * @deprecated see {@link MessageMode#containedIn(byte)} */ public static final boolean isDefaultMode(byte esmClass) { return isMessagingMode(esmClass, SMPPConstant.ESMCLS_DEFAULT_MODE); } /** * Messaging Mode. * * @param esmClass * @return * @deprecated use {@link MessageMode#compose(byte, MessageMode)} */ public static final byte composeDefaultMode(byte esmClass) { return composeMessagingMode(esmClass, SMPPConstant.ESMCLS_DEFAULT_MODE); } /** * Messaging Mode. * * @param esmClass * @return */ public static final boolean isDatagramMode(byte esmClass) { return isMessagingMode(esmClass, SMPPConstant.ESMCLS_DATAGRAM_MODE); } /** * Messaging Mode. * * @param esmClass * @return */ public static final byte composeDatagramMode(byte esmClass) { return composeMessagingMode(esmClass, SMPPConstant.ESMCLS_DATAGRAM_MODE); } /** * Messaging Mode. * * @param esmClass * @return */ public static final boolean isForwardMode(byte esmClass) { return isMessagingMode(esmClass, SMPPConstant.ESMCLS_FORWARD_MODE); } /** * Messaging Mode. * * @param esmClass * @return */ public static final byte composeForwardMode(byte esmClass) { return composeMessagingMode(esmClass, SMPPConstant.ESMCLS_FORWARD_MODE); } /** * Messaging Mode. * * @param esmClass * @return */ public static final boolean isStoreAndForwardMode(byte esmClass) { return isMessagingMode(esmClass, SMPPConstant.ESMCLS_STORE_FORWARD); } /** * Messaging Mode. * * @param esmClass * @return */ public static final byte composeStoreAndForwardMode(byte esmClass) { return composeMessagingMode(esmClass, SMPPConstant.ESMCLS_STORE_FORWARD); } /** * Message Type. * * @param esmClass * @return */ public static final boolean isEsmeDeliveryAcknowledgement(byte esmClass) { return isMessageType(esmClass, SMPPConstant.ESMCLS_ESME_DELIVERY_ACK); } /** * Message Type. * * @param esmClass * @return */ public static final byte composeEsmeDeliveryAcknowledgement(byte esmClass) { return composeMessageType(esmClass, SMPPConstant.ESMCLS_ESME_DELIVERY_ACK); } /** * Message Type. * * @param esmClass * @return */ public static final boolean isEsmeManualAcknowledgement(byte esmClass) { return isMessageType(esmClass, SMPPConstant.ESMCLS_ESME_MANUAL_ACK); } /** * Message Type. * * @param esmClass * @return */ public static final byte composeEsmeManualAcknowledgement(byte esmClass) { return composeMessageType(esmClass, SMPPConstant.ESMCLS_ESME_MANUAL_ACK); } /** * SMSC Delivery Receipt. * * @param registeredDelivery * @return */ public static final boolean isSmscDelNotRequested(byte registeredDelivery) { return isSmscDeliveryReceipt(registeredDelivery, SMPPConstant.REGDEL_SMSC_NO); } public static final byte composeSmscDelReceiptNotRequested( byte registeredDelivery) { return composeSmscDelReceipt(registeredDelivery, SMPPConstant.REGDEL_SMSC_NO); } /** * SMSC Delivery Receipt. * * @param registeredDelivery * @return */ public static final boolean isSmscDelReceiptSuccessAndFailureRequested( byte registeredDelivery) { return isSmscDeliveryReceipt(registeredDelivery, SMPPConstant.REGDEL_SMSC_SUCCESS_FAILURE_REQUESTED); } public static final byte composeSmscDelReceiptSuccessAndFailureRequested( byte registeredDelivery) { return composeSmscDelReceipt(registeredDelivery, SMPPConstant.REGDEL_SMSC_SUCCESS_FAILURE_REQUESTED); } /** * SMSC Delivery Receipt. * * @param registeredDelivery * @return */ public static final boolean isSmscDelReceiptFailureRequested( byte registeredDelivery) { return isSmscDeliveryReceipt(registeredDelivery, SMPPConstant.REGDEL_SMSC_FAILURE_REQUESTED); } public static final byte composeSmscDelReceiptFailureRequested( byte registeredDelivery) { return composeSmscDelReceipt(registeredDelivery, SMPPConstant.REGDEL_SMSC_FAILURE_REQUESTED); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/SubmitSmResp.java000066400000000000000000000013401246113105100233560ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class SubmitSmResp extends AbstractSmRespCommand { public SubmitSmResp() { super(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/SubmitSmValue.java000066400000000000000000000166261246113105100235360ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class SubmitSmValue { private String _serviceType; private byte _sourceAddrTon; private byte _sourceAddrNpi; private String _sourceAddr; private byte _destAddrTon; private byte _destAddrNpi; private String _destinationAddr; private byte _esmClass; private byte _protocolId; private byte _priorityFlag; private String _scheduleDeliveryTime; private String _validityPeriod; private byte _registeredDelivery; private byte _replaceIfPresent; private byte _dataCoding; private byte _smDefaultMsgId; private String _shortMessage; public SubmitSmValue() { } public SubmitSmValue(String serviceType, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte destAddrTon, byte destAddrNpi, String destinationAddr, byte esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, byte registeredDelivery, byte replaceIfPresent, byte dataCoding, byte smDefaultMsgId, String shortMessage) { _serviceType = serviceType; _sourceAddrTon = sourceAddrTon; _sourceAddrNpi = sourceAddrNpi; _sourceAddr = sourceAddr; _destAddrTon = destAddrTon; _destAddrNpi = destAddrNpi; _destinationAddr = destinationAddr; _esmClass = esmClass; _protocolId = protocolId; _priorityFlag = priorityFlag; _scheduleDeliveryTime = scheduleDeliveryTime; _validityPeriod = validityPeriod; _registeredDelivery = registeredDelivery; _replaceIfPresent = replaceIfPresent; _dataCoding = dataCoding; _smDefaultMsgId = smDefaultMsgId; _shortMessage = shortMessage; } /** * @return Returns the dataCoding. */ public byte getDataCoding() { return _dataCoding; } /** * @param dataCoding The dataCoding to set. */ public void setDataCoding(byte dataCoding) { _dataCoding = dataCoding; } /** * @return Returns the destAddrNpi. */ public byte getDestAddrNpi() { return _destAddrNpi; } /** * @param destAddrNpi The destAddrNpi to set. */ public void setDestAddrNpi(byte destAddrNpi) { _destAddrNpi = destAddrNpi; } /** * @return Returns the destAddrTon. */ public byte getDestAddrTon() { return _destAddrTon; } /** * @param destAddrTon The destAddrTon to set. */ public void setDestAddrTon(byte destAddrTon) { _destAddrTon = destAddrTon; } /** * @return Returns the destinationAddr. */ public String getDestinationAddr() { return _destinationAddr; } /** * @param destinationAddr The destinationAddr to set. */ public void setDestinationAddr(String destinationAddr) { _destinationAddr = destinationAddr; } /** * @return Returns the esmClass. */ public byte getEsmClass() { return _esmClass; } /** * @param esmClass The esmClass to set. */ public void setEsmClass(byte esmClass) { _esmClass = esmClass; } /** * @return Returns the priorityFlag. */ public byte getPriorityFlag() { return _priorityFlag; } /** * @param priorityFlag The priorityFlag to set. */ public void setPriorityFlag(byte priorityFlag) { _priorityFlag = priorityFlag; } /** * @return Returns the protocolId. */ public byte getProtocolId() { return _protocolId; } /** * @param protocolId The protocolId to set. */ public void setProtocolId(byte protocolId) { _protocolId = protocolId; } /** * @return Returns the registeredDelivery. */ public byte getRegisteredDelivery() { return _registeredDelivery; } /** * @param registeredDelivery The registeredDelivery to set. */ public void setRegisteredDelivery(byte registeredDelivery) { _registeredDelivery = registeredDelivery; } /** * @return Returns the replaceIfPresent. */ public byte getReplaceIfPresent() { return _replaceIfPresent; } /** * @param replaceIfPresent The replaceIfPresent to set. */ public void setReplaceIfPresent(byte replaceIfPresent) { _replaceIfPresent = replaceIfPresent; } /** * @return Returns the scheduleDeliveryTime. */ public String getScheduleDeliveryTime() { return _scheduleDeliveryTime; } /** * @param scheduleDeliveryTime The scheduleDeliveryTime to set. */ public void setScheduleDeliveryTime(String scheduleDeliveryTime) { _scheduleDeliveryTime = scheduleDeliveryTime; } /** * @return Returns the serviceType. */ public String getServiceType() { return _serviceType; } /** * @param serviceType The serviceType to set. */ public void setServiceType(String serviceType) { _serviceType = serviceType; } /** * @return Returns the shortMessage. */ public String getShortMessage() { return _shortMessage; } /** * @param shortMessage The shortMessage to set. */ public void setShortMessage(String shortMessage) { _shortMessage = shortMessage; } /** * @return Returns the smDefaultMsgId. */ public byte getSmDefaultMsgId() { return _smDefaultMsgId; } /** * @param smDefaultMsgId The smDefaultMsgId to set. */ public void setSmDefaultMsgId(byte smDefaultMsgId) { _smDefaultMsgId = smDefaultMsgId; } /** * @return Returns the sourceAddr. */ public String getSourceAddr() { return _sourceAddr; } /** * @param sourceAddr The sourceAddr to set. */ public void setSourceAddr(String sourceAddr) { _sourceAddr = sourceAddr; } /** * @return Returns the sourceAddrNpi. */ public byte getSourceAddrNpi() { return _sourceAddrNpi; } /** * @param sourceAddrNpi The sourceAddrNpi to set. */ public void setSourceAddrNpi(byte sourceAddrNpi) { _sourceAddrNpi = sourceAddrNpi; } /** * @return Returns the sourceAddrTon. */ public byte getSourceAddrTon() { return _sourceAddrTon; } /** * @param sourceAddrTon The sourceAddrTon to set. */ public void setSourceAddrTon(byte sourceAddrTon) { _sourceAddrTon = sourceAddrTon; } /** * @return Returns the validityPeriod. */ public String getValidityPeriod() { return _validityPeriod; } /** * @param validityPeriod The validityPeriod to set. */ public void setValidityPeriod(String validityPeriod) { _validityPeriod = validityPeriod; } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/TypeOfNumber.java000066400000000000000000000036021246113105100233430ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; import org.jsmpp.SMPPConstant; /** * Type of Number based on SMPP version 3.4. * * @author uudashr * @version 1.0 * @since 1.0 * */ public enum TypeOfNumber { UNKNOWN(SMPPConstant.TON_UNKNOWN), INTERNATIONAL(SMPPConstant.TON_INTERNATIONAL), NATIONAL(SMPPConstant.TON_NATIONAL), NETWORK_SPECIFIC(SMPPConstant.TON_NETWORK_SPECIFIC), SUBSCRIBER_NUMBER(SMPPConstant.TON_SUBSCRIBER_NUMBER), ALPHANUMERIC(SMPPConstant.TON_ALPHANUMERIC), ABBREVIATED(SMPPConstant.TON_ABBREVIATED); private byte value; private TypeOfNumber(byte value) { this.value = value; } /** * Get the byte value of the enum constant. * * @return the byte value. */ public byte value() { return value; } /** * Get the TypeOfNumber based on the specified byte value * representation. * * @param value is the byte value representation. * @return is the enum const related to the specified byte value. * @throws IllegalArgumentException if there is no enum const associated * with specified byte value. */ public static TypeOfNumber valueOf(byte value) { for (TypeOfNumber val : values()) { if (val.value == value) return val; } throw new IllegalArgumentException( "No enum const TypeOfNumber with value " + value); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/Unbind.java000066400000000000000000000013101246113105100221750ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class Unbind extends Command { public Unbind() { super(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/UnbindResp.java000066400000000000000000000013201246113105100230300ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class UnbindResp extends Command { public UnbindResp() { super(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/bean/UnsuccessDelivery.java000066400000000000000000000043171246113105100244470ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * @author uudashr * */ public class UnsuccessDelivery { private Address destinationAddress; private int errorStatusCode; public UnsuccessDelivery(byte destAddrTon, byte destAddrNpi, String destAddress, int errorStatusCode) { this(new Address(destAddrTon, destAddrNpi, destAddress), errorStatusCode); } public UnsuccessDelivery(Address destinationAddress, int errorStatusCode) { this.destinationAddress = destinationAddress; this.errorStatusCode = errorStatusCode; } public Address getDestinationAddress() { return destinationAddress; } public int getErrorStatusCode() { return errorStatusCode; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((destinationAddress == null) ? 0 : destinationAddress .hashCode()); result = prime * result + errorStatusCode; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final UnsuccessDelivery other = (UnsuccessDelivery)obj; if (destinationAddress == null) { if (other.destinationAddress != null) return false; } else if (!destinationAddress.equals(other.destinationAddress)) return false; if (errorStatusCode != other.errorStatusCode) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/extra/000077500000000000000000000000001246113105100203365ustar00rootroot00000000000000jsmpp-2.1.2/src/main/java/org/jsmpp/extra/NegativeResponseException.java000066400000000000000000000015211246113105100263400ustar00rootroot00000000000000package org.jsmpp.extra; import org.jsmpp.util.IntUtil; /** * This exception is thrown if we receive an negative response. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class NegativeResponseException extends Exception { private static final long serialVersionUID = 7198456791204091251L; private int commandStatus; /** * Construct with specified command_status. * * @param commandStatus is the command_status. */ public NegativeResponseException(int commandStatus) { super("Negative response " + IntUtil.toHexString(commandStatus) + " found"); this.commandStatus = commandStatus; } /** * Get the command_status. * * @return is the command_status. */ public int getCommandStatus() { return commandStatus; } } jsmpp-2.1.2/src/main/java/org/jsmpp/extra/PendingResponse.java000066400000000000000000000063241246113105100243110ustar00rootroot00000000000000package org.jsmpp.extra; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.jsmpp.InvalidResponseException; import org.jsmpp.bean.Command; /** * This class is utility that able wait for a response for specified timeout. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class PendingResponse { private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private long timeout; private T response; private InvalidResponseException illegalResponseException; /** * Construct with specified timeout. * * @param timeout is the timeout in millisecond. */ public PendingResponse(long timeout) { this.timeout = timeout; } /** * Check whether if we already receive response. * * @return true if response already receive. */ private boolean isDoneResponse() { return response != null; } /** * Done with valid response and notify that response already received. * * @param response is the response. * @throws IllegalArgumentException thrown if response is null. */ public void done(T response) throws IllegalArgumentException { lock.lock(); try { if (response != null) { this.response = response; condition.signal(); } else { throw new IllegalArgumentException("response cannot be null"); } } finally { lock.unlock(); } } /** * Done with invalid response (negative response/non OK command_status). * * @param e is the {@link InvalidResponseException}. */ public void doneWithInvalidResponse(InvalidResponseException e) { lock.lock(); try { illegalResponseException = e; condition.signal(); } finally { lock.unlock(); } } /** * Get the response. * * @return the response. */ public T getResponse() { lock.lock(); try { return response; } finally { lock.unlock(); } } /** * Wait until response receive or timeout already reach. * * @throws ResponseTimeoutException if timeout reach. * @throws InvalidResponseException if receive invalid response. */ public void waitDone() throws ResponseTimeoutException, InvalidResponseException { lock.lock(); try { if (!isDoneResponse()) { try { condition.await(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } } if (illegalResponseException != null) { throw illegalResponseException; } if (!isDoneResponse()) { throw new ResponseTimeoutException("No response after " + timeout + " millis"); } } finally { lock.unlock(); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/extra/ProcessRequestException.java000066400000000000000000000023331246113105100260500ustar00rootroot00000000000000package org.jsmpp.extra; /** * Thrown if there is an error occur when processing request. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class ProcessRequestException extends Exception { private static final long serialVersionUID = -3633100382131187197L; private final int errorCode; /** * Construct with specified message and error code. * * @param message is the detail message. * @param errorCode is the error code (or known as command_status). */ public ProcessRequestException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Construct with specified message, error code, and cause. * * @param message is the detail message. * @param errorCode is the error code (or known as command_status). * @param cause is the parent cause. */ public ProcessRequestException(String message, int errorCode, Throwable cause) { super(message, cause); this.errorCode = errorCode; } /** * Get the error code (or known as command_status). * * @return the error code. */ public int getErrorCode() { return errorCode; } } jsmpp-2.1.2/src/main/java/org/jsmpp/extra/QueueException.java000066400000000000000000000017011246113105100241430ustar00rootroot00000000000000package org.jsmpp.extra; /** * General queue exception. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class QueueException extends Exception { private static final long serialVersionUID = -8946319349013591134L; /** * Default constructor. */ public QueueException() { super(); } /** * Construct with specified message and cause. * * @param message is the detail message. * @param cause is the cause. */ public QueueException(String message, Throwable cause) { super(message, cause); } /** * Construct with specified message. * * @param message is the detail message. */ public QueueException(String message) { super(message); } /** * Construct with specified cause. * * @param cause is the cause of an error. */ public QueueException(Throwable cause) { super(cause); } } jsmpp-2.1.2/src/main/java/org/jsmpp/extra/QueueMaxException.java000066400000000000000000000020161246113105100246110ustar00rootroot00000000000000package org.jsmpp.extra; /** * This exception is thrown if the message queue has reach it maximum size. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class QueueMaxException extends QueueException { private static final long serialVersionUID = 5811663728783767496L; /** * Default constructor. */ public QueueMaxException() { super(); } /** * Construct with specified detail messsage and cause. * * @param message is the detail message. * @param cause is the parent cause. */ public QueueMaxException(String message, Throwable cause) { super(message, cause); } /** * Construct with specified message. * * @param message is the detail message. */ public QueueMaxException(String message) { super(message); } /** * Construct with specified cause. * * @param cause is the parent cause. */ public QueueMaxException(Throwable cause) { super(cause); } } jsmpp-2.1.2/src/main/java/org/jsmpp/extra/ResponseTimeoutException.java000066400000000000000000000020021246113105100262170ustar00rootroot00000000000000package org.jsmpp.extra; /** * Throw if the the response never come for specified timeout. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class ResponseTimeoutException extends Exception { private static final long serialVersionUID = 2091678783085990727L; /** * Default constructor. */ public ResponseTimeoutException() { super(); } /** * Construct with specified message and cause. * * @param message is the message. * @param cause is the cause. */ public ResponseTimeoutException(String message, Throwable cause) { super(message, cause); } /** * Construct with specified message. * * @param message is the detail message. */ public ResponseTimeoutException(String message) { super(message); } /** * Construct with specified cause. * * @param cause is the cause. */ public ResponseTimeoutException(Throwable cause) { super(cause); } } jsmpp-2.1.2/src/main/java/org/jsmpp/extra/SessionState.java000066400000000000000000000030441246113105100236260ustar00rootroot00000000000000package org.jsmpp.extra; /** * Enum constant represent session state. * * @author uudashr * @version 1.0 * @since 1.0 * */ public enum SessionState { /** * Open, means connection has established but not bounded. */ OPEN, /** * Bound transmitter, means bound transmit has been initiated. */ BOUND_TX, /** * Bound receiver, means bound receive has been initiated. */ BOUND_RX, /** * Bound transceiver, means bound transceive has been initiated. */ BOUND_TRX, /** * Unbound, means unbound has been initiated but the connection hasn't been * closed. */ UNBOUND, /** * There is no connection at all. */ CLOSED, /** * Outbound, means the session is in outbound state, ready to initiate * bound. */ OUTBOUND; /** * Check whether the session state is bound. * * @return true if session state is bound state */ public boolean isBound() { return equals(BOUND_RX) || equals(BOUND_TX) || equals(BOUND_TRX); } /** * Check whether the session state is transmittable. * * @return true if session is transmittable. */ public boolean isTransmittable() { return equals(BOUND_TX) || equals(BOUND_TRX); } /** * Check whether the session state is receivable. * * @return true if session is receivable. */ public boolean isReceivable() { return equals(BOUND_RX) || equals(BOUND_TRX); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/000077500000000000000000000000001246113105100206765ustar00rootroot00000000000000jsmpp-2.1.2/src/main/java/org/jsmpp/session/AbstractSMPPOperation.java000066400000000000000000000174321246113105100256740ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.util.Hashtable; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.PDUSender; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.Command; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.DataSmResp; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.PendingResponse; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.session.connection.Connection; import org.jsmpp.util.Sequence; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author uudashr * */ public abstract class AbstractSMPPOperation implements SMPPOperation { private static final Logger logger = LoggerFactory.getLogger(AbstractSMPPOperation.class); private final Hashtable> pendingResponse = new Hashtable>(); private final Sequence sequence = new Sequence(1); private final PDUSender pduSender; private final Connection connection; private long transactionTimer = 2000; public AbstractSMPPOperation(Connection connection, PDUSender pduSender) { this.connection = connection; this.pduSender = pduSender; } protected PDUSender pduSender() { return pduSender; } protected Connection connection() { return connection; } public void setTransactionTimer(long transactionTimer) { this.transactionTimer = transactionTimer; } public long getTransactionTimer() { return transactionTimer; } /** * Execute send command command task. * * @param task is the task. * @param timeout is the timeout in millisecond. * @return the command response. * @throws PDUException if there is invalid PDU parameter found. * @throws ResponseTimeoutException if the response has reach it timeout. * @throws InvalidResponseException if invalid response found. * @throws NegativeResponseException if the negative response found. * @throws IOException if there is an IO error found. */ protected Command executeSendCommand(SendCommandTask task, long timeout) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { int seqNum = sequence.nextValue(); PendingResponse pendingResp = new PendingResponse(timeout); pendingResponse.put(seqNum, pendingResp); try { task.executeTask(connection().getOutputStream(), seqNum); } catch (IOException e) { logger.error("Failed sending " + task.getCommandName() + " command", e); pendingResponse.remove(seqNum); throw e; } try { pendingResp.waitDone(); logger.debug(task.getCommandName() + " response received"); } catch (ResponseTimeoutException e) { pendingResponse.remove(seqNum); logger.debug("Response timeout for " + task.getCommandName() + " with sessionIdSequence number " + seqNum); throw e; } catch (InvalidResponseException e) { pendingResponse.remove(seqNum); throw e; } Command resp = pendingResp.getResponse(); validateResponse(resp); return resp; } /** * Validate the response, the command_status should be 0 otherwise will * throw {@link NegativeResponseException}. * * @param response is the response. * @throws NegativeResponseException if the command_status value is not zero. */ private static void validateResponse(Command response) throws NegativeResponseException { if (response.getCommandStatus() != SMPPConstant.STAT_ESME_ROK) { throw new NegativeResponseException(response.getCommandStatus()); } } public void unbind() throws ResponseTimeoutException, InvalidResponseException, IOException { UnbindCommandTask task = new UnbindCommandTask(pduSender); try { executeSendCommand(task, transactionTimer); } catch (PDUException e) { // exception should be never caught since we didn't send any string parameter. logger.warn("PDU String should be always valid", e); } catch (NegativeResponseException e) { // ignore the negative response logger.warn("Receive non-ok command_status (" + e.getCommandStatus() + ") for unbind_resp"); } } public void unbindResp(int sequenceNumber) throws IOException { pduSender.sendUnbindResp(connection().getOutputStream(), SMPPConstant.STAT_ESME_ROK, sequenceNumber); } public DataSmResult dataSm(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, RegisteredDelivery registeredDelivery, DataCoding dataCoding, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { DataSmCommandTask task = new DataSmCommandTask(pduSender, serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, registeredDelivery, dataCoding, optionalParameters); DataSmResp resp = (DataSmResp)executeSendCommand(task, getTransactionTimer()); return new DataSmResult(resp.getMessageId(), resp.getOptionalParameters()); } public void dataSmResp(int sequenceNumber, String messageId, OptionalParameter... optionalParameters) throws PDUStringException, IOException { pduSender.sendDataSmResp(connection().getOutputStream(), sequenceNumber, messageId, optionalParameters); } public void enquireLink() throws ResponseTimeoutException, InvalidResponseException, IOException { EnquireLinkCommandTask task = new EnquireLinkCommandTask(pduSender); try { executeSendCommand(task, getTransactionTimer()); } catch (PDUException e) { // should never happen, since it doesn't have any String parameter. logger.warn("PDU String should be always valid", e); } catch (NegativeResponseException e) { // the command_status of the response should be always 0 logger.warn("command_status of response should be always 0", e); } } public void enquireLinkResp(int sequenceNumber) throws IOException { pduSender.sendEnquireLinkResp(connection().getOutputStream(), sequenceNumber); } public void genericNack(int commandStatus, int sequenceNumber) throws IOException { pduSender.sendGenericNack(connection().getOutputStream(), commandStatus, sequenceNumber); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/AbstractSendCommandTask.java000066400000000000000000000016221246113105100262410ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.PDUSender; /** * Abstract send command task. * * @author uudashr * */ public abstract class AbstractSendCommandTask implements SendCommandTask { protected final PDUSender pduSender; public AbstractSendCommandTask(PDUSender pduSender) { this.pduSender = pduSender; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/AbstractSession.java000066400000000000000000000312271246113105100246550ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.PDUSender; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.Command; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.DataSm; import org.jsmpp.bean.DataSmResp; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.PendingResponse; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.extra.SessionState; import org.jsmpp.session.connection.Connection; import org.jsmpp.util.IntUtil; import org.jsmpp.util.Sequence; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author uudashr * */ public abstract class AbstractSession implements Session { private static final Logger logger = LoggerFactory.getLogger(AbstractSession.class); private static final Random random = new Random(); private final Map> pendingResponse = new ConcurrentHashMap>(); private final Sequence sequence = new Sequence(1); private final PDUSender pduSender; private int pduProcessorDegree = 3; private String sessionId = generateSessionId(); private int enquireLinkTimer = 5000; private long transactionTimer = 2000; public AbstractSession(PDUSender pduSender) { this.pduSender = pduSender; } protected abstract AbstractSessionContext sessionContext(); protected abstract Connection connection(); protected abstract GenericMessageReceiverListener messageReceiverListener(); protected PDUSender pduSender() { return pduSender; } protected Sequence sequence() { return sequence; } protected PendingResponse removePendingResponse(int sequenceNumber) { return pendingResponse.remove(sequenceNumber); } public String getSessionId() { return sessionId; } public void setEnquireLinkTimer(int enquireLinkTimer) { if (sessionContext().getSessionState().isBound()) { try { connection().setSoTimeout(enquireLinkTimer); } catch (IOException e) { logger.error("Failed setting so_timeout for session timer", e); } } this.enquireLinkTimer = enquireLinkTimer; } public int getEnquireLinkTimer() { return enquireLinkTimer; } public void setTransactionTimer(long transactionTimer) { this.transactionTimer = transactionTimer; } public long getTransactionTimer() { return transactionTimer; } public SessionState getSessionState() { return sessionContext().getSessionState(); } public void addSessionStateListener(SessionStateListener l) { if (l != null) { sessionContext().addSessionStateListener(l); } } public void removeSessionStateListener(SessionStateListener l) { sessionContext().removeSessionStateListener(l); } public long getLastActivityTimestamp() { return sessionContext().getLastActivityTimestamp(); } /** * Set total thread can read PDU and process it parallely. It's defaulted to * 3. * * @param pduProcessorDegree is the total thread can handle read and process * PDU parallely. * @throws IllegalStateException if the PDU Reader has been started. */ public void setPduProcessorDegree(int pduProcessorDegree) throws IllegalStateException { if (!getSessionState().equals(SessionState.CLOSED)) { throw new IllegalStateException( "Cannot set pdu processor degree since the pdu dispatcher thread already created."); } this.pduProcessorDegree = pduProcessorDegree; } /** * Get the total of thread that can handle read and process PDU parallely. * * @return the total of thread that can handle read and process PDU * parallely. */ public int getPduProcessorDegree() { return pduProcessorDegree; } /** * Send the data_sm command. * * @param serviceType is the service_type parameter. * @param sourceAddrTon is the source_addr_ton parameter. * @param sourceAddrNpi is the source_addr_npi parameter. * @param sourceAddr is the source_addr parameter. * @param destAddrTon is the dest_addr_ton parameter. * @param destAddrNpi is the dest_addr_npi parameter. * @param destinationAddr is the destination_addr parameter. * @param esmClass is the esm_class parameter. * @param registeredDelivery is the registered_delivery parameter. * @param dataCoding is the data_coding parameter. * @param optionalParameters is the optional parameters. * @return the result of data_sm (data_sm_resp). * @throws PDUException if there is an invalid PDU parameter found. * @throws ResponseTimeoutException if the response take time too long. * @throws InvalidResponseException if the response is invalid. * @throws NegativeResponseException if the response return NON-OK command_status. * @throws IOException if there is an IO error found. */ public DataSmResult dataShortMessage(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, RegisteredDelivery registeredDelivery, DataCoding dataCoding, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { DataSmCommandTask task = new DataSmCommandTask(pduSender, serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, registeredDelivery, dataCoding, optionalParameters); DataSmResp resp = (DataSmResp)executeSendCommand(task, getTransactionTimer()); return new DataSmResult(resp.getMessageId(), resp.getOptionalParameters()); } public void close() { SessionContext ctx = sessionContext(); if (!ctx.getSessionState().equals(SessionState.CLOSED)) { ctx.close(); try { connection().close(); } catch (IOException e) { } } } /** * Validate the response, the command_status should be 0 otherwise will * throw {@link NegativeResponseException}. * * @param response is the response. * @throws NegativeResponseException if the command_status value is not zero. */ private static void validateResponse(Command response) throws NegativeResponseException { if (response.getCommandStatus() != SMPPConstant.STAT_ESME_ROK) { throw new NegativeResponseException(response.getCommandStatus()); } } protected DataSmResult fireAcceptDataSm(DataSm dataSm) throws ProcessRequestException { GenericMessageReceiverListener messageReceiverListener = messageReceiverListener(); if (messageReceiverListener != null) { return messageReceiverListener.onAcceptDataSm(dataSm, this); } else { throw new ProcessRequestException("MessageReceveiverListener hasn't been set yet", SMPPConstant.STAT_ESME_RX_R_APPN); } } /** * Execute send command command task. * * @param task is the task. * @param timeout is the timeout in millisecond. * @return the command response. * @throws PDUException if there is invalid PDU parameter found. * @throws ResponseTimeoutException if the response has reach it timeout. * @throws InvalidResponseException if invalid response found. * @throws NegativeResponseException if the negative response found. * @throws IOException if there is an IO error found. */ protected Command executeSendCommand(SendCommandTask task, long timeout) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { int seqNum = sequence.nextValue(); PendingResponse pendingResp = new PendingResponse(timeout); pendingResponse.put(seqNum, pendingResp); try { task.executeTask(connection().getOutputStream(), seqNum); } catch (IOException e) { logger.error("Failed sending " + task.getCommandName() + " command", e); pendingResponse.remove(seqNum); close(); throw e; } try { pendingResp.waitDone(); logger.debug(task.getCommandName() + " response received"); } catch (ResponseTimeoutException e) { pendingResponse.remove(seqNum); throw new ResponseTimeoutException("No response after waiting for " + timeout + " millis when executing " + task.getCommandName() + " with sessionId " + sessionId + " and sequenceNumber " + seqNum, e); } catch (InvalidResponseException e) { pendingResponse.remove(seqNum); throw e; } Command resp = pendingResp.getResponse(); validateResponse(resp); return resp; } private synchronized static final String generateSessionId() { return IntUtil.toHexString(random.nextInt()); } /** * Ensure we have proper link. * * @throws ResponseTimeoutException if there is no valid response after defined millisecond. * @throws InvalidResponseException if there is invalid response found. * @throws IOException if there is an IO error found. */ protected void sendEnquireLink() throws ResponseTimeoutException, InvalidResponseException, IOException { EnquireLinkCommandTask task = new EnquireLinkCommandTask(pduSender); try { executeSendCommand(task, getTransactionTimer()); } catch (PDUException e) { // should never happen, since it doesn't have any String parameter. logger.warn("PDU String should be always valid", e); } catch (NegativeResponseException e) { // the command_status of the response should be always 0 logger.warn("command_status of response should be always 0", e); } } private void unbind() throws ResponseTimeoutException, InvalidResponseException, IOException { if (sessionContext().getSessionState().equals(SessionState.CLOSED)) { throw new IOException("Session is closed"); } UnbindCommandTask task = new UnbindCommandTask(pduSender); try { executeSendCommand(task, transactionTimer); } catch (PDUException e) { // exception should be never caught since we didn't send any string parameter. logger.warn("PDU String should be always valid", e); } catch (NegativeResponseException e) { // ignore the negative response logger.warn("Receive non-ok command_status (" + e.getCommandStatus() + ") for unbind_resp"); } } public void unbindAndClose() { if (sessionContext().getSessionState().isBound()) { try { unbind(); } catch (ResponseTimeoutException e) { logger.error("Timeout waiting unbind response", e); } catch (InvalidResponseException e) { logger.error("Receive invalid unbind response", e); } catch (IOException e) { logger.error("IO error found ", e); } } close(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/AbstractSessionContext.java000066400000000000000000000055621246113105100262250ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.util.concurrent.CopyOnWriteArrayList; import java.util.List; import org.jsmpp.bean.BindType; import org.jsmpp.extra.SessionState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author uudashr * */ public abstract class AbstractSessionContext implements SessionContext { private static final Logger logger = LoggerFactory.getLogger(AbstractSessionContext.class); private long lastActivityTimestamp; private List sessionStateListeners = new CopyOnWriteArrayList(); public AbstractSessionContext() { } public AbstractSessionContext(SessionStateListener sessionStateListener) { sessionStateListeners.add(sessionStateListener); } public synchronized void open() { changeState(SessionState.OPEN); } public synchronized void bound(BindType bindType) { if (bindType.equals(BindType.BIND_TX)) { changeState(SessionState.BOUND_TX); } else if (bindType.equals(BindType.BIND_RX)) { changeState(SessionState.BOUND_RX); } else if (bindType.equals(BindType.BIND_TRX)) { changeState(SessionState.BOUND_TRX); } else { throw new IllegalArgumentException("Bind type " + bindType + " not supported"); } } public synchronized void unbound() { changeState(SessionState.UNBOUND); } public synchronized void close() { changeState(SessionState.CLOSED); } public void addSessionStateListener( SessionStateListener l) { sessionStateListeners.add(l); } public void removeSessionStateListener(SessionStateListener l) { sessionStateListeners.remove(l); } protected void fireStateChanged(SessionState newState, SessionState oldState, Object source) { for (SessionStateListener l : sessionStateListeners) { l.onStateChange(newState, oldState, source); } } public void notifyActivity() { logger.debug("Activity notified"); lastActivityTimestamp = System.currentTimeMillis(); } public long getLastActivityTimestamp() { return lastActivityTimestamp; } protected abstract void changeState(SessionState newState); } jsmpp-2.1.2/src/main/java/org/jsmpp/session/ActivityNotifier.java000066400000000000000000000014501246113105100250350ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; /** * Class responsible to accept the notification of an activity. * * @author uudashr * */ public interface ActivityNotifier { /** * Notify an activity. */ void notifyActivity(); } jsmpp-2.1.2/src/main/java/org/jsmpp/session/BaseResponseHandler.java000066400000000000000000000065701246113105100254400ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.bean.Command; import org.jsmpp.bean.DataSm; import org.jsmpp.extra.PendingResponse; import org.jsmpp.extra.ProcessRequestException; /** * @author uudashr * */ public interface BaseResponseHandler { /** * Remove the previously {@link PendingResponse} that set when the request * was sent. * * @param sequenceNumber the sequence number of the request. * @return the {@link PendingResponse} correspond to specified * sequenceNumber. Return null if the the mapped * sequenceNumber not found */ PendingResponse removeSentItem(int sequenceNumber); /** * Response by sending GENERICK_NACK. * * @param commandStatus is the command status. * @param sequenceNumber is the sequence number original PDU if can be decoded. * @throws IOException if an IO error occur. */ void sendGenerickNack(int commandStatus, int sequenceNumber) throws IOException; /** * Response by sending negative response. * * @param originalCommandId is the original command id. * @param commandStatus is the command status. * @param sequenceNumber is the sequence number of original PDU request. * @throws IOException if an IO error occur. */ void sendNegativeResponse(int originalCommandId, int commandStatus, int sequenceNumber) throws IOException; /** * Response by sending ENQUIRE_LINK_RESP. * * @param sequenceNumber is the sequence number of original ENQUIRE_LINK * request. * @throws IOException if an IO error occur. */ void sendEnquireLinkResp(int sequenceNumber) throws IOException; /** * Response by send UNBIND_RESP. * * @param sequenceNumber is the sequence number of original UNBIND request. * @throws IOException if an IO error occur. */ void sendUnbindResp(int sequenceNumber) throws IOException; /** * Process the data short message. * * @param dataSm is the data short message. * @return the result for response. * @throws ProcessRequestException if there is a failure when processing * data_sm. */ DataSmResult processDataSm(DataSm dataSm) throws ProcessRequestException; /** * Response by sending DATA_SM_RESP to SMSC. * * @param dataSmResult is the result of data_sm. * @param sequenceNumber is the sequence number of original DATA_SM * request. * @throws IOException if an IO error occur. */ public void sendDataSmResp(DataSmResult dataSmResult, int sequenceNumber) throws IOException; /** * Notify for unbind. */ void notifyUnbonded(); } jsmpp-2.1.2/src/main/java/org/jsmpp/session/BindCommandTask.java000066400000000000000000000043331246113105100245420ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.PDUSender; import org.jsmpp.PDUStringException; import org.jsmpp.bean.BindType; import org.jsmpp.bean.InterfaceVersion; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.TypeOfNumber; /** * @author uudashr * */ public class BindCommandTask extends AbstractSendCommandTask { private final BindType bindType; private final String systemId; private final String password; private final String systemType; private final InterfaceVersion interfaceVersion; private final TypeOfNumber addrTon; private final NumberingPlanIndicator addrNpi; private final String addressRange; public BindCommandTask(PDUSender pduSender, BindType bindType, String systemId, String password, String systemType, InterfaceVersion interfaceVersion, TypeOfNumber addrTon, NumberingPlanIndicator addrNpi, String addressRange) { super(pduSender); this.bindType = bindType; this.systemId = systemId; this.password = password; this.systemType = systemType; this.interfaceVersion = interfaceVersion; this.addrTon = addrTon; this.addrNpi = addrNpi; this.addressRange = addressRange; } public void executeTask(OutputStream out, int sequenceNumber) throws PDUStringException, IOException { pduSender.sendBind(out, bindType, sequenceNumber, systemId, password, systemType, interfaceVersion, addrTon, addrNpi, addressRange); } public String getCommandName() { return "bind"; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/BindParameter.java000066400000000000000000000131611246113105100242600ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.bean.BindType; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.TypeOfNumber; /** * This class is wraps all bind parameter that will be send as PDU. * * @author uudashr * */ public class BindParameter { private BindType bindType; private String systemId; private String password; private String systemType; private TypeOfNumber addrTon; private NumberingPlanIndicator addrNpi; private String addressRange; /** * Construct with all mandatory parameters. * * @param bindType is the bind type. * @param systemId is the system id. * @param password is the password. * @param systemType is the system type. * @param addrTon is the address TON. * @param addrNpi is the address NPI. * @param addressRange is the address range. */ public BindParameter(BindType bindType, String systemId, String password, String systemType, TypeOfNumber addrTon, NumberingPlanIndicator addrNpi, String addressRange) { this.bindType = bindType; this.systemId = systemId; this.password = password; this.systemType = systemType; this.addrTon = addrTon; this.addrNpi = addrNpi; this.addressRange = addressRange; } public BindType getBindType() { return bindType; } public String getSystemId() { return systemId; } public String getPassword() { return password; } public String getSystemType() { return systemType; } public TypeOfNumber getAddrTon() { return addrTon; } public NumberingPlanIndicator getAddrNpi() { return addrNpi; } public String getAddressRange() { return addressRange; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((addrNpi == null) ? 0 : addrNpi.hashCode()); result = prime * result + ((addrTon == null) ? 0 : addrTon.hashCode()); result = prime * result + ((addressRange == null) ? 0 : addressRange.hashCode()); result = prime * result + ((bindType == null) ? 0 : bindType.hashCode()); result = prime * result + ((password == null) ? 0 : password.hashCode()); result = prime * result + ((systemId == null) ? 0 : systemId.hashCode()); result = prime * result + ((systemType == null) ? 0 : systemType.hashCode()); return result; } private boolean hasEqualAddrNpi(BindParameter other) { if (addrNpi == null) { if (other.addrNpi != null) { return false; } } return addrNpi.equals(other.addrNpi); } private boolean hasEqualAddrTon(BindParameter other) { if (addrTon == null) { if (other.addrTon != null) { return false; } } return addrTon.equals(other.addrTon); } private boolean hasEqualAddressRange(BindParameter other) { if (addressRange == null) { if (other.addressRange != null) { return false; } } return addressRange.equals(other.addressRange); } private boolean hasEqualBindType(BindParameter other) { if (bindType == null) { if (other.bindType != null) { return false; } } return bindType.equals(other.bindType); } private boolean hasEqualPassword(BindParameter other) { if (password == null) { if (other.password != null) { return false; } } return password.equals(other.password); } private boolean hasEqualSystemId(BindParameter other) { if (systemId == null) { if (other.systemId != null) { return false; } } return systemId.equals(other.systemId); } private boolean hasEqualSystemType(BindParameter other) { if (systemType == null) { if (other.systemType != null) { return false; } } return systemType.equals(other.systemType); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final BindParameter other = (BindParameter)obj; if (!hasEqualAddrNpi(other)) { return false; } if (!hasEqualAddrTon(other)) { return false; } if (!hasEqualAddressRange(other)) { return false; } if (!hasEqualBindType(other)) { return false; } if (!hasEqualPassword(other)) { return false; } if (!hasEqualSystemId(other)) { return false; } if (!hasEqualSystemType(other)) { return false; } return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/BindRequest.java000066400000000000000000000123061246113105100237700ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.jsmpp.PDUStringException; import org.jsmpp.bean.Bind; import org.jsmpp.bean.BindType; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.util.StringParameter; import org.jsmpp.util.StringValidator; /** * @author uudashr * */ public class BindRequest { private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private final BindType bindType; private final String systemId; private final String password; private final String systemType; private final TypeOfNumber addrTon; private final NumberingPlanIndicator addrNpi; private final String addressRange; private final int originalSequenceNumber; private boolean done; private final ServerResponseHandler responseHandler; public BindRequest(int sequenceNumber, BindType bindType, String systemId, String password, String systemType, TypeOfNumber addrTon, NumberingPlanIndicator addrNpi, String addressRange, ServerResponseHandler responseHandler) { this.originalSequenceNumber = sequenceNumber; this.responseHandler = responseHandler; this.bindType = bindType; this.systemId = systemId; this.password = password; this.systemType = systemType; this.addrTon = addrTon; this.addrNpi = addrNpi; this.addressRange = addressRange; } public BindRequest(Bind bind, ServerResponseHandler responseHandler) { this(bind.getSequenceNumber(), BindType.valueOf(bind.getCommandId()), bind.getSystemId(), bind.getPassword(), bind.getSystemType(), TypeOfNumber.valueOf(bind.getAddrTon()), NumberingPlanIndicator.valueOf(bind.getAddrNpi()), bind.getAddressRange(), responseHandler); } @Deprecated public BindParameter getBindParameter() { return new BindParameter(bindType, systemId, password, systemType, addrTon, addrNpi, addressRange); } public BindType getBindType() { return bindType; } public String getSystemId() { return systemId; } public String getPassword() { return password; } public String getSystemType() { return systemType; } public TypeOfNumber getAddrTon() { return addrTon; } public NumberingPlanIndicator getAddrNpi() { return addrNpi; } public String getAddressRange() { return addressRange; } /** * Accept the bind request. * * @param systemId is the system identifier that will be send to ESME. * @throws PDUStringException if the system id is not valid. * @throws IllegalStateException if the acceptance or rejection has been made. * @throws IOException is the connection already closed. * @see #reject(ProcessRequestException) */ public void accept(String systemId) throws PDUStringException, IllegalStateException, IOException { StringValidator.validateString(systemId, StringParameter.SYSTEM_ID); lock.lock(); try { if (!done) { done = true; try { responseHandler.sendBindResp(systemId, bindType, originalSequenceNumber); } finally { condition.signal(); } } else { throw new IllegalStateException("Response already initiated"); } } finally { lock.unlock(); } done = true; } /** * Reject the bind request. * * @param errorCode is the reason of rejection. * @throws IllegalStateException if the acceptance or rejection has been made. * @throws IOException if the connection already closed. * @see {@link #accept()} */ public void reject(int errorCode) throws IllegalStateException, IOException { lock.lock(); try { if (done) { throw new IllegalStateException("Response already initiated"); } else { done = true; try { responseHandler.sendNegativeResponse(bindType.commandId(), errorCode, originalSequenceNumber); } finally { condition.signal(); } } } finally { lock.unlock(); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/BindRequestReceiver.java000066400000000000000000000057571246113105100254710ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.jsmpp.bean.Bind; /** * @author uudashr * */ class BindRequestReceiver { private final Lock lock = new ReentrantLock(); private final Condition requestCondition = lock.newCondition(); private final ServerResponseHandler responseHandler; private BindRequest request; private boolean alreadyWaitForRequest; public BindRequestReceiver(ServerResponseHandler responseHandler) { this.responseHandler = responseHandler; } /** * Wait until the bind request received for specified timeout. * * @param timeout is the timeout. * @return the {@link BindRequest}. * @throws IllegalStateException if this method already called before. * @throws TimeoutException if the timeout has been reach. */ BindRequest waitForRequest(long timeout) throws IllegalStateException, TimeoutException { lock.lock(); try { if (alreadyWaitForRequest) { throw new IllegalStateException("waitForRequest(long) method already invoked"); } else if (request == null) { try { requestCondition.await(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } } if (request != null) { return request; } else { throw new TimeoutException("Wating for bind request take time too long"); } } finally { alreadyWaitForRequest = true; lock.unlock(); } } /** * Notify that the bind has accepted. * * @param bindParameter is the {@link Bind} command. * @throws IllegalStateException if this method already called before. */ void notifyAcceptBind(Bind bindParameter) throws IllegalStateException { lock.lock(); try { if (request == null) { request = new BindRequest(bindParameter, responseHandler); requestCondition.signal(); } else { throw new IllegalStateException("Already waiting for acceptance bind"); } } finally { lock.unlock(); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/BindResult.java000066400000000000000000000021431246113105100236140ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.bean.OptionalParameter; /** * @author uudashr * */ public class BindResult { private String messageId; private OptionalParameter[] optionalParameter; public BindResult(String messageId, OptionalParameter[] optionalParameter) { this.messageId = messageId; this.optionalParameter = optionalParameter; } public String getMessageId() { return messageId; } public OptionalParameter[] getOptionalParameter() { return optionalParameter; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/CancelSmCommandTask.java000066400000000000000000000043341246113105100253540ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.PDUSender; import org.jsmpp.PDUStringException; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.TypeOfNumber; /** * @author uudashr * */ public class CancelSmCommandTask extends AbstractSendCommandTask { private String serviceType; private String messageId; private TypeOfNumber sourceAddrTon; private NumberingPlanIndicator sourceAddrNpi; private String sourceAddr; private TypeOfNumber destAddrTon; private NumberingPlanIndicator destAddrNpi; private String destinationAddress; public CancelSmCommandTask(PDUSender pduSender, String serviceType, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddress) { super(pduSender); this.serviceType = serviceType; this.messageId = messageId; this.sourceAddrTon = sourceAddrTon; this.sourceAddrNpi = sourceAddrNpi; this.sourceAddr = sourceAddr; this.destAddrTon = destAddrTon; this.destAddrNpi = destAddrNpi; this.destinationAddress = destinationAddress; } public void executeTask(OutputStream out, int sequenceNumber) throws PDUStringException, IOException { pduSender.sendCancelSm(out, sequenceNumber, serviceType, messageId, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddress); } public String getCommandName() { return "cancel_sm"; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/ClientSession.java000066400000000000000000000241401246113105100243240ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.bean.Address; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.ReplaceIfPresentFlag; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; /** * This interface provides all operation that the client session can do. It * doesn't distinct the operation of specific session type (Transmitter, * Receiver) it's just like Transceiver. The distinction might should be * recognized in a different way, such as by user code when they do a binding or * by throwing exception when invoking illegal operation. * * @author uudashr * */ public interface ClientSession extends Session { /** * Submit a short message to specified destination address. This method will * blocks until response received or timeout reached. This method simplify * operations of sending SUBMIT_SM command and receiving the SUBMIT_SM_RESP. * * @param serviceType is the service_type. * @param sourceAddrTon is the source_addr_ton. * @param sourceAddrNpi is the source_addr_npi. * @param sourceAddr is the source_addr. * @param destAddrTon is the dest_addr_ton. * @param destAddrNpi is the dest_addr_npi. * @param destinationAddr is the destination_addr. * @param esmClass is the esm_class. * @param protocolId is the protocol_id. * @param priorityFlag is the priority_flag. * @param scheduleDeliveryTime is the schedule_delivery_time. * @param validityPeriod is the validity_period. * @param registeredDelivery is the registered_delivery. * @param replaceIfPresentFlag is the replace_if_present_flag. * @param dataCoding is the data_coding. * @param smDefaultMsgId is the sm_default_msg_id. * @param shortMessage is the short_message. * @param optionalParameters is the optional parameters. * @return the message_id to identified the submitted short message for * later use (delivery receipt, QUERY_SM, CANCEL_SM, REPLACE_SM). * @throws PDUException if there is invalid PDU parameter found.. * @throws ResponseTimeoutException if timeout has been reach. * @throws InvalidResponseException if response is invalid. * @throws NegativeResponseException if negative response received. * @throws IOException if there is an I/O error found. */ String submitShortMessage(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; /** * Submit short message to multiple destination address. It's similar to * submit short message, but it sending to multiple address. This method * will blocks until response received or timeout reached. This method is * simplify operations of sending SUBMIT_MULTI and receiving * SUBMIT_MULTI_RESP. * * @param serviceType is the service_type. * @param sourceAddrTon is the source_addr_ton. * @param sourceAddrNpi is the source_addr_npi. * @param sourceAddr is the source_addr. * @param destinationAddresses is the destination addresses. * @param esmClass is the esm_class. * @param protocolId is the protocol_id. * @param priorityFlag is the priority_flag. * @param scheduleDeliveryTime is the schedule_delivery_time. * @param validityPeriod is the validity_period. * @param registeredDelivery is the registered_delivery. * @param replaceIfPresentFlag is the replace_if_present_flag. * @param dataCoding is the data_coding. * @param smDefaultMsgId is the sm_default_msg_id. * @param shortMessage is the short_message. * @param optionalParameters is the optional parameters. * @return the message_id and the un-success deliveries. * @throws PDUException if there is invalid PDU parameter found. * @throws ResponseTimeoutException if timeout has been reach. * @throws InvalidResponseException if response is invalid. * @throws NegativeResponseException if negative response received. * @throws IOException if there is an I/O error found. */ SubmitMultiResult submitMultiple(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, Address[] destinationAddresses, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, ReplaceIfPresentFlag replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter[] optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; /** * Query previous submitted short message based on it's message_id and * message_id. This method will blocks until response received or timeout * reached. This method is simplify operations of sending QUERY_SM and * receiving QUERY_SM_RESP. * * @param messageId is the message_id. * @param sourceAddrTon is the source_addr_ton. * @param sourceAddrNpi is the source_addr_npi. * @param sourceAddr is the source_addr. * @return the result of query short message. * @throws PDUException if there is invalid PDU parameter found. * @throws ResponseTimeoutException if timeout has been reach. * @throws InvalidResponseException if response is invalid. * @throws NegativeResponseException if negative response received. * @throws IOException if there is an I/O error found. */ QuerySmResult queryShortMessage(String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; /** * Cancel the previous submitted short message. This method will blocks * until response received or timeout reached. This method is simplify * operations of sending CANCEL_SM and receiving CANCEL_SM_RESP. * * @param serviceType is the service_type. * @param messageId is the message_id. * @param sourceAddrTon is the source_addr_ton. * @param sourceAddrNpi is the source_addr_npi. * @param sourceAddr is the source_addr. * @param destAddrTon is the dest_addr_ton. * @param destAddrNpi is the dest_addr_npi. * @param destinationAddress is destination_address. * @throws PDUException if there is invalid PDU parameter found. * @throws ResponseTimeoutException if timeout has been reach. * @throws InvalidResponseException if response is invalid. * @throws NegativeResponseException if negative response received. * @throws IOException if there is an I/O error found. */ void cancelShortMessage(String serviceType, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddress) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; /** * Replace the previous submitted short message. This method will blocks * until response received or timeout reached. This method is simplify * operations of sending REPLACE_SM and receiving REPLACE_SM_RESP. * * @param messageId is the message_id. * @param sourceAddrTon is the source_addr_ton. * @param sourceAddrNpi is the source_addr_npi. * @param sourceAddr is the source_addr. * @param scheduleDeliveryTime is the schedule_delivery_time. * @param validityPeriod is the validity_period. * @param registeredDelivery is the registered_delivery. * @param smDefaultMsgId is the sm_default_msg_id. * @param shortMessage is the short_message. * @throws PDUException if there is invalid PDU parameter found. * @throws ResponseTimeoutException if timeout has been reach. * @throws InvalidResponseException if response is invalid. * @throws NegativeResponseException if negative response received. * @throws IOException if there is an I/O error found. */ void replaceShortMessage(String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte smDefaultMsgId, byte[] shortMessage) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/DataSmCommandTask.java000066400000000000000000000056331246113105100250430ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.PDUSender; import org.jsmpp.PDUStringException; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; /** * @author uudashr * */ public class DataSmCommandTask extends AbstractSendCommandTask { private final String serviceType; private final TypeOfNumber sourceAddrTon; private final NumberingPlanIndicator sourceAddrNpi; private final String sourceAddr; private final TypeOfNumber destAddrTon; private final NumberingPlanIndicator destAddrNpi; private final String destinationAddr; private final ESMClass esmClass; private final RegisteredDelivery registeredDelivery; private final DataCoding dataCoding; private final OptionalParameter[] optionalParameters; public DataSmCommandTask(PDUSender pduSender, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, RegisteredDelivery registeredDelivery, DataCoding dataCoding, OptionalParameter[] optionalParameters) { super(pduSender); this.serviceType = serviceType; this.sourceAddrTon = sourceAddrTon; this.sourceAddrNpi = sourceAddrNpi; this.sourceAddr = sourceAddr; this.destAddrTon = destAddrTon; this.destAddrNpi = destAddrNpi; this.destinationAddr = destinationAddr; this.esmClass = esmClass; this.registeredDelivery = registeredDelivery; this.dataCoding = dataCoding; this.optionalParameters = optionalParameters; } public void executeTask(OutputStream out, int sequenceNumber) throws PDUStringException, IOException { pduSender.sendDataSm(out, sequenceNumber, serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, registeredDelivery, dataCoding, optionalParameters); } public String getCommandName() { return "data_sm"; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/DataSmResult.java000066400000000000000000000024621246113105100241150ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.util.MessageId; /** * @author uudashr * */ public class DataSmResult { private final String messageId; private final OptionalParameter[] optionalParameters; DataSmResult(String messageId, OptionalParameter[] optionalParameters) { this.messageId = messageId; this.optionalParameters = optionalParameters; } public DataSmResult(MessageId messageId, OptionalParameter[] optionalParameters) { this(messageId.getValue(), optionalParameters); } public String getMessageId() { return messageId; } public OptionalParameter[] getOptionalParameters() { return optionalParameters; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/DefaultSMPPClientOperation.java000066400000000000000000000171471246113105100266570ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.PDUSender; import org.jsmpp.PDUStringException; import org.jsmpp.bean.Address; import org.jsmpp.bean.BindResp; import org.jsmpp.bean.BindType; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.InterfaceVersion; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.QuerySmResp; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.ReplaceIfPresentFlag; import org.jsmpp.bean.SubmitMultiResp; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.SubmitSmResp; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.session.connection.Connection; /** * @author uudashr * */ public class DefaultSMPPClientOperation extends AbstractSMPPOperation implements SMPPClientOperation { public DefaultSMPPClientOperation(Connection connection, PDUSender pduSender) { super(connection, pduSender); } public BindResult bind(BindType bindType, String systemId, String password, String systemType, InterfaceVersion interfaceVersion, TypeOfNumber addrTon, NumberingPlanIndicator addrNpi, String addressRange, long timeout) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { BindCommandTask task = new BindCommandTask(pduSender(), bindType, systemId, password, systemType, interfaceVersion, addrTon, addrNpi, addressRange); BindResp resp = (BindResp)executeSendCommand(task, timeout); return new BindResult(resp.getSystemId(), resp.getOptionalParameters()); } public String submitSm(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { SubmitSmCommandTask submitSmTask = new SubmitSmCommandTask( pduSender(), serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, protocolId, priorityFlag, scheduleDeliveryTime, validityPeriod, registeredDelivery, replaceIfPresentFlag, dataCoding, smDefaultMsgId, shortMessage, optionalParameters); SubmitSmResp resp = (SubmitSmResp)executeSendCommand(submitSmTask, getTransactionTimer()); return resp.getMessageId(); } public SubmitMultiResult submitMulti(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, Address[] destinationAddresses, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, ReplaceIfPresentFlag replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter[] optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { SubmitMultiCommandTask task = new SubmitMultiCommandTask(pduSender(), serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destinationAddresses, esmClass, protocolId, priorityFlag, scheduleDeliveryTime, validityPeriod, registeredDelivery, replaceIfPresentFlag, dataCoding, smDefaultMsgId, shortMessage, optionalParameters); SubmitMultiResp resp = (SubmitMultiResp)executeSendCommand(task, getTransactionTimer()); return new SubmitMultiResult(resp.getMessageId(), resp .getUnsuccessSmes()); } public QuerySmResult querySm(String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { QuerySmCommandTask task = new QuerySmCommandTask(pduSender(), messageId, sourceAddrTon, sourceAddrNpi, sourceAddr); QuerySmResp resp = (QuerySmResp)executeSendCommand(task, getTransactionTimer()); if (resp.getMessageId().equals(messageId)) { return new QuerySmResult(resp.getFinalDate(), resp .getMessageState(), resp.getErrorCode()); } else { // message id requested not same as the returned throw new InvalidResponseException( "Requested message_id doesn't match with the result"); } } public void cancelSm(String serviceType, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddress) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { CancelSmCommandTask task = new CancelSmCommandTask(pduSender(), serviceType, messageId, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddress); executeSendCommand(task, getTransactionTimer()); } public void replaceSm(String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte smDefaultMsgId, byte[] shortMessage) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { ReplaceSmCommandTask replaceSmTask = new ReplaceSmCommandTask( pduSender(), messageId, sourceAddrTon, sourceAddrNpi, sourceAddr, scheduleDeliveryTime, validityPeriod, registeredDelivery, smDefaultMsgId, shortMessage); executeSendCommand(replaceSmTask, getTransactionTimer()); } public void deliverSmResp(int sequenceNumber) throws IOException { pduSender().sendDeliverSmResp(connection().getOutputStream(), sequenceNumber); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/DefaultSMPPServerOperation.java000066400000000000000000000102301246113105100266710ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.PDUSender; import org.jsmpp.PDUStringException; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.MessageState; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.bean.UnsuccessDelivery; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.session.connection.Connection; import org.jsmpp.util.MessageId; /** * @author uudashr * */ public class DefaultSMPPServerOperation extends AbstractSMPPOperation implements SMPPServerOperation { public DefaultSMPPServerOperation(Connection connection, PDUSender pduSender) { super(connection, pduSender); } public void deliverSm(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocoId, byte priorityFlag, RegisteredDelivery registeredDelivery, DataCoding dataCoding, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { DeliverSmCommandTask task = new DeliverSmCommandTask(pduSender(), serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, protocoId, protocoId, registeredDelivery, dataCoding, shortMessage, optionalParameters); executeSendCommand(task, getTransactionTimer()); } public void alertNotification(int sequenceNumber, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber esmeAddrTon, NumberingPlanIndicator esmeAddrNpi, String esmeAddr, OptionalParameter... optionalParameters) throws PDUException, IOException { pduSender().sendAlertNotification(connection().getOutputStream(), sequenceNumber, sourceAddrTon.value(), sourceAddrNpi.value(), sourceAddr, esmeAddrTon.value(), esmeAddrNpi.value(), esmeAddr, optionalParameters); } public void querySmResp(String messageId, String finalDate, MessageState messageState, byte errorCode, int sequenceNumber) throws PDUException, IOException { pduSender().sendQuerySmResp(connection().getOutputStream(), sequenceNumber, messageId, finalDate, messageState, errorCode); } public void replaceSmResp(int sequenceNumber) throws IOException { pduSender().sendReplaceSmResp(connection().getOutputStream(), sequenceNumber); } public void submitMultiResp(int sequenceNumber, String messageId, UnsuccessDelivery... unsuccessDeliveries) throws PDUException, IOException { pduSender().sendSubmitMultiResp(connection().getOutputStream(), sequenceNumber, messageId, unsuccessDeliveries); } public void submitSmResp(MessageId messageId, int sequenceNumber) throws PDUException, IOException { pduSender().sendSubmitSmResp(connection().getOutputStream(), sequenceNumber, messageId.getValue()); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/DeliverSmCommandTask.java000066400000000000000000000064301246113105100255600ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.PDUSender; import org.jsmpp.PDUStringException; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; /** * @author uudashr * */ public class DeliverSmCommandTask extends AbstractSendCommandTask { private final String serviceType; private final TypeOfNumber sourceAddrTon; private final NumberingPlanIndicator sourceAddrNpi; private final String sourceAddr; private final TypeOfNumber destAddrTon; private final NumberingPlanIndicator destAddrNpi; private final String destinationAddr; private final ESMClass esmClass; private final byte protocoId; private final byte priorityFlag; private final RegisteredDelivery registeredDelivery; private final DataCoding dataCoding; private final byte[] shortMessage; private final OptionalParameter[] optionalParameters; public DeliverSmCommandTask(PDUSender pduSender, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocoId, byte priorityFlag, RegisteredDelivery registeredDelivery, DataCoding dataCoding, byte[] shortMessage, OptionalParameter[] optionalParameters) { super(pduSender); this.serviceType = serviceType; this.sourceAddrTon = sourceAddrTon; this.sourceAddrNpi = sourceAddrNpi; this.sourceAddr = sourceAddr; this.destAddrTon = destAddrTon; this.destAddrNpi = destAddrNpi; this.destinationAddr = destinationAddr; this.esmClass = esmClass; this.protocoId = protocoId; this.priorityFlag = priorityFlag; this.registeredDelivery = registeredDelivery; this.dataCoding = dataCoding; this.shortMessage = shortMessage; this.optionalParameters = optionalParameters; } public void executeTask(OutputStream out, int sequenceNumber) throws PDUStringException, IOException { pduSender.sendDeliverSm(out, sequenceNumber, serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, protocoId, priorityFlag, registeredDelivery, dataCoding, shortMessage, optionalParameters); } public String getCommandName() { return "deliver_sm"; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/EnquireLinkCommandTask.java000066400000000000000000000021411246113105100261070ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.PDUSender; /** * @author uudashr * */ public class EnquireLinkCommandTask extends AbstractSendCommandTask { public EnquireLinkCommandTask(PDUSender pduSender) { super(pduSender); } public void executeTask(OutputStream out, int sequenceNumber) throws IOException { pduSender.sendEnquireLink(out, sequenceNumber); } public String getCommandName() { return "enquire_link"; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/GenericMessageReceiverListener.java000066400000000000000000000031711246113105100276170ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.bean.DataSm; import org.jsmpp.extra.ProcessRequestException; /** * This listener will listen to every incoming short message. The logic of this * method event should be accomplish in a short time, because the the other * event will be waiting the invocation of the method. Normal logic will be * return the response with zero valued command_status, or throw * {@link ProcessRequestException} if the non-zero valued command_status (in * means negative response) returned. * * @author uudashr * @version 1.0 * @since 2.0 * */ public interface GenericMessageReceiverListener { /** * Event that called when a data short message accepted. * * @param dataSm is the data_sm command. * @param source is the session receive the data_sm command. * @return the data_sm result. * @throws ProcessRequestException throw if there should be return non-ok * command_status for the response. */ DataSmResult onAcceptDataSm(DataSm dataSm, Session source) throws ProcessRequestException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/MessageReceiverListener.java000066400000000000000000000036471246113105100263320ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.bean.AlertNotification; import org.jsmpp.bean.DeliverSm; import org.jsmpp.extra.ProcessRequestException; /** * This listener will listen to every incoming short message, recognized by * deliver_sm command. The logic on this listener should be accomplish in a * short time, because the deliver_sm_resp will be processed after the logic * executed. Normal logic will be return the deliver_sm_resp with zero valued * command_status, or throw {@link ProcessRequestException} that gave non-zero * valued command_status (in means negative response) depends on the given error * code specified on the {@link ProcessRequestException}. * * @author uudashr * @version 1.0 * @since 2.0 * */ public interface MessageReceiverListener extends GenericMessageReceiverListener { /** * This event raised when a short message received. * * @param deliverSm is the short message. * @throws ProcessRequestException throw if there should be return Non-OK * command_status for the response. */ void onAcceptDeliverSm(DeliverSm deliverSm) throws ProcessRequestException; /** * This event raised when alert notification received. * * @param alertNotification is the alert notification. */ void onAcceptAlertNotification(AlertNotification alertNotification); } jsmpp-2.1.2/src/main/java/org/jsmpp/session/PDUProcessServerTask.java000066400000000000000000000114021246113105100255400ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.Command; import org.jsmpp.session.state.SMPPServerSessionState; /** * @author uudashr * */ public class PDUProcessServerTask implements Runnable { private final Command pduHeader; private final byte[] pdu; private final SMPPServerSessionState stateProcessor; private final ActivityNotifier activityNotifier; private final ServerResponseHandler responseHandler; private final Runnable onIOExceptionTask; public PDUProcessServerTask(Command pduHeader, byte[] pdu, SMPPServerSessionState stateProcessor, ActivityNotifier activityNotifier, ServerResponseHandler responseHandler, Runnable onIOExceptionTask) { this.pduHeader = pduHeader; this.pdu = pdu; this.stateProcessor = stateProcessor; this.activityNotifier = activityNotifier; this.responseHandler = responseHandler; this.onIOExceptionTask = onIOExceptionTask; } public void run() { try { switch (pduHeader.getCommandId()) { case SMPPConstant.CID_BIND_RECEIVER: case SMPPConstant.CID_BIND_TRANSMITTER: case SMPPConstant.CID_BIND_TRANSCEIVER: activityNotifier.notifyActivity(); stateProcessor.processBind(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_GENERIC_NACK: activityNotifier.notifyActivity(); stateProcessor.processGenericNack(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_ENQUIRE_LINK: activityNotifier.notifyActivity(); stateProcessor.processEnquireLink(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_ENQUIRE_LINK_RESP: activityNotifier.notifyActivity(); stateProcessor.processEnquireLinkResp(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_SUBMIT_SM: activityNotifier.notifyActivity(); stateProcessor.processSubmitSm(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_SUBMIT_MULTI: activityNotifier.notifyActivity(); stateProcessor.processSubmitMulti(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_QUERY_SM: activityNotifier.notifyActivity(); stateProcessor.processQuerySm(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_DELIVER_SM_RESP: activityNotifier.notifyActivity(); stateProcessor.processDeliverSmResp(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_DATA_SM: activityNotifier.notifyActivity(); stateProcessor.processDataSm(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_DATA_SM_RESP: activityNotifier.notifyActivity(); stateProcessor.processDataSmResp(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_CANCEL_SM: activityNotifier.notifyActivity(); stateProcessor.processCancelSm(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_REPLACE_SM: activityNotifier.notifyActivity(); stateProcessor.processReplaceSm(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_UNBIND: activityNotifier.notifyActivity(); stateProcessor.processUnbind(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_UNBIND_RESP: activityNotifier.notifyActivity(); stateProcessor.processUnbindResp(pduHeader, pdu, responseHandler); break; default: stateProcessor.processUnknownCid(pduHeader, pdu, responseHandler); } } catch (IOException e) { onIOExceptionTask.run(); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/PDUProcessTask.java000066400000000000000000000117301246113105100243550ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.Command; import org.jsmpp.session.state.SMPPSessionState; /** * @author uudashr * */ public class PDUProcessTask implements Runnable { private final Command pduHeader; private final byte[] pdu; private final SMPPSessionState stateProcessor; private final ResponseHandler responseHandler; private final ActivityNotifier activityNotifier; private final Runnable onIOExceptionTask; public PDUProcessTask(Command pduHeader, byte[] pdu, SMPPSessionState stateProcessor, ResponseHandler responseHandler, ActivityNotifier activityNotifier, Runnable onIOExceptionTask) { this.pduHeader = pduHeader; this.pdu = pdu; this.stateProcessor = stateProcessor; this.responseHandler = responseHandler; this.activityNotifier = activityNotifier; this.onIOExceptionTask = onIOExceptionTask; } public void run() { try { switch (pduHeader.getCommandId()) { case SMPPConstant.CID_BIND_RECEIVER_RESP: case SMPPConstant.CID_BIND_TRANSMITTER_RESP: case SMPPConstant.CID_BIND_TRANSCEIVER_RESP: activityNotifier.notifyActivity(); stateProcessor.processBindResp(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_GENERIC_NACK: activityNotifier.notifyActivity(); stateProcessor.processGenericNack(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_ENQUIRE_LINK: activityNotifier.notifyActivity(); stateProcessor.processEnquireLink(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_ENQUIRE_LINK_RESP: activityNotifier.notifyActivity(); stateProcessor.processEnquireLinkResp(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_SUBMIT_SM_RESP: activityNotifier.notifyActivity(); stateProcessor.processSubmitSmResp(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_SUBMIT_MULTI_RESP: activityNotifier.notifyActivity(); stateProcessor.processSubmitMultiResp(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_QUERY_SM_RESP: activityNotifier.notifyActivity(); stateProcessor.processQuerySmResp(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_DELIVER_SM: activityNotifier.notifyActivity(); stateProcessor.processDeliverSm(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_DATA_SM: activityNotifier.notifyActivity(); stateProcessor.processDataSm(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_DATA_SM_RESP: activityNotifier.notifyActivity(); stateProcessor.processDataSmResp(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_CANCEL_SM_RESP: activityNotifier.notifyActivity(); stateProcessor.processCancelSmResp(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_REPLACE_SM_RESP: activityNotifier.notifyActivity(); stateProcessor.processReplaceSmResp(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_ALERT_NOTIFICATION: activityNotifier.notifyActivity(); stateProcessor.processAlertNotification(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_UNBIND: activityNotifier.notifyActivity(); stateProcessor.processUnbind(pduHeader, pdu, responseHandler); break; case SMPPConstant.CID_UNBIND_RESP: activityNotifier.notifyActivity(); stateProcessor.processUnbindResp(pduHeader, pdu, responseHandler); break; default: stateProcessor.processUnknownCid(pduHeader, pdu, responseHandler); } } catch (IOException e) { onIOExceptionTask.run(); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/QuerySmCommandTask.java000066400000000000000000000033651246113105100252770ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.PDUSender; import org.jsmpp.PDUStringException; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.TypeOfNumber; /** * @author uudashr * */ public class QuerySmCommandTask extends AbstractSendCommandTask { private final String messageId; private final TypeOfNumber sourceAddrTon; private final NumberingPlanIndicator sourceAddrNpi; private final String sourceAddr; public QuerySmCommandTask(PDUSender pduSender, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr) { super(pduSender); this.messageId = messageId; this.sourceAddrTon = sourceAddrTon; this.sourceAddrNpi = sourceAddrNpi; this.sourceAddr = sourceAddr; } public void executeTask(OutputStream out, int sequenceNumber) throws PDUStringException, IOException { pduSender.sendQuerySm(out, sequenceNumber, messageId, sourceAddrTon, sourceAddrNpi, sourceAddr); } public String getCommandName() { return "query_sm"; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/QuerySmResult.java000066400000000000000000000051321246113105100243460ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.bean.MessageState; /** * Result of query short message. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class QuerySmResult { private final String finalDate; private final MessageState messageState; private final byte errorCode; public QuerySmResult(String finalDate, MessageState messageState, byte errorCode) { this.finalDate = finalDate; this.messageState = messageState; this.errorCode = errorCode; } /** * @return the errorCode */ public byte getErrorCode() { return errorCode; } /** * @return the finalDate */ public String getFinalDate() { return finalDate; } /** * @return the messageState */ public MessageState getMessageState() { return messageState; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((finalDate == null) ? 0 : finalDate.hashCode()); result = PRIME * result + ((messageState == null) ? 0 : messageState.hashCode()); return result; } private boolean hasEqualFinalDate(QuerySmResult other) { if (finalDate == null) { if (other.finalDate != null) { return false; } } return finalDate.equals(other.finalDate); } private boolean hasEqualMessageState(QuerySmResult other) { if (messageState == null) { if (other.messageState != null) { return false; } } return messageState.equals(other.messageState); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final QuerySmResult other = (QuerySmResult) obj; if (errorCode != other.errorCode) return false; if (!hasEqualFinalDate(other)) { return false; } if (!hasEqualMessageState(other)) { return false; } return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/ReplaceSmCommandTask.java000066400000000000000000000046751246113105100255520ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.PDUSender; import org.jsmpp.PDUStringException; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; public class ReplaceSmCommandTask extends AbstractSendCommandTask { private String messageId; private TypeOfNumber sourceAddrTon; private NumberingPlanIndicator sourceAddrNpi; private String sourceAddr; private String scheduleDeliveryTime; private String validityPeriod; private RegisteredDelivery registeredDelivery; private byte smDefaultMsgId; private byte[] shortMessage; public ReplaceSmCommandTask(PDUSender pduSender, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte smDefaultMsgId, byte[] shortMessage) { super(pduSender); this.messageId = messageId; this.sourceAddrTon = sourceAddrTon; this.sourceAddrNpi = sourceAddrNpi; this.sourceAddr = sourceAddr; this.scheduleDeliveryTime = scheduleDeliveryTime; this.validityPeriod = validityPeriod; this.registeredDelivery = registeredDelivery; this.smDefaultMsgId = smDefaultMsgId; this.shortMessage = shortMessage; } public void executeTask(OutputStream out, int sequenceNumber) throws PDUStringException, IOException { pduSender.sendReplaceSm(out, sequenceNumber, messageId, sourceAddrTon, sourceAddrNpi, sourceAddr, scheduleDeliveryTime, validityPeriod, registeredDelivery, smDefaultMsgId, shortMessage); } public String getCommandName() { return "replace_sm"; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/ResponseHandler.java000066400000000000000000000030121246113105100246310ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.bean.AlertNotification; import org.jsmpp.bean.DeliverSm; import org.jsmpp.extra.ProcessRequestException; /** * ResponseHandler provide interface to handle response of the session * routines. * * @author uudashr * @version 1.0 * @since 2.0 * */ public interface ResponseHandler extends BaseResponseHandler { /** * Process the deliver * * @param deliverSm * @throws ProcessRequestException */ void processDeliverSm(DeliverSm deliverSm) throws ProcessRequestException; /** * Response by sending DELIVER_SM_RESP to SMSC. * * @param sequenceNumber is the sequence number of original DELIVER_SM request. * @throws IOException if an IO error occur. */ void sendDeliverSmResp(int sequenceNumber) throws IOException; void processAlertNotification(AlertNotification alertNotification); } jsmpp-2.1.2/src/main/java/org/jsmpp/session/SMPPClientOperation.java000066400000000000000000000103621246113105100253420ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.PDUStringException; import org.jsmpp.bean.Address; import org.jsmpp.bean.BindType; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.InterfaceVersion; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.ReplaceIfPresentFlag; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; /** * @author uudashr * */ public interface SMPPClientOperation extends SMPPOperation { BindResult bind(BindType bindType, String systemId, String password, String systemType, InterfaceVersion interfaceVersion, TypeOfNumber addrTon, NumberingPlanIndicator addrNpi, String addressRange, long timeout) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; String submitSm(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; SubmitMultiResult submitMulti(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, Address[] destinationAddresses, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, ReplaceIfPresentFlag replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter[] optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; QuerySmResult querySm(String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; void cancelSm(String serviceType, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddress) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; void replaceSm(String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte smDefaultMsgId, byte[] shortMessage) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; void deliverSmResp(int sequenceNumber) throws IOException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/SMPPOperation.java000066400000000000000000000043371246113105100242100ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.PDUStringException; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; /** * @author uudashr * */ public interface SMPPOperation { void unbind() throws ResponseTimeoutException, InvalidResponseException, IOException; void unbindResp(int sequenceNumber) throws IOException; DataSmResult dataSm(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, RegisteredDelivery registeredDelivery, DataCoding dataCoding, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; void dataSmResp(int sequenceNumber, String messageId, OptionalParameter... optionalParameters) throws PDUStringException, IOException; void enquireLink() throws ResponseTimeoutException, InvalidResponseException, IOException; void enquireLinkResp(int sequenceNumber) throws IOException; void genericNack(int commandStatus, int sequenceNumber) throws IOException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/SMPPServerOperation.java000066400000000000000000000051751246113105100254000ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.MessageState; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.bean.UnsuccessDelivery; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.util.MessageId; /** * @author uudashr * */ public interface SMPPServerOperation extends SMPPOperation { void deliverSm(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocoId, byte priorityFlag, RegisteredDelivery registeredDelivery, DataCoding dataCoding, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; void alertNotification(int sequenceNumber, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber esmeAddrTon, NumberingPlanIndicator esmeAddrNpi, String esmeAddr, OptionalParameter... optionalParameters) throws PDUException, IOException; void submitSmResp(MessageId messageId, int sequenceNumber) throws PDUException, IOException; void submitMultiResp(int sequenceNumber, String messageId, UnsuccessDelivery... unsuccessDeliveries) throws PDUException, IOException; void querySmResp(String messageId, String finalDate, MessageState messageState, byte errorCode, int sequenceNumber) throws PDUException, IOException; void replaceSmResp(int sequenceNumber) throws IOException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/SMPPServerSession.java000066400000000000000000000526531246113105100250660ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.SocketTimeoutException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import org.jsmpp.DefaultPDUReader; import org.jsmpp.DefaultPDUSender; import org.jsmpp.InvalidCommandLengthException; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.PDUReader; import org.jsmpp.PDUSender; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.SynchronizedPDUSender; import org.jsmpp.bean.Bind; import org.jsmpp.bean.BindType; import org.jsmpp.bean.CancelSm; import org.jsmpp.bean.Command; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.DataSm; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.MessageState; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.QuerySm; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.ReplaceSm; import org.jsmpp.bean.SubmitMulti; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.SubmitSm; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.PendingResponse; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.extra.SessionState; import org.jsmpp.session.connection.Connection; import org.jsmpp.util.MessageId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author uudashr * */ public class SMPPServerSession extends AbstractSession implements ServerSession { private static final Logger logger = LoggerFactory.getLogger(SMPPServerSession.class); private final Connection conn; private final DataInputStream in; private final OutputStream out; private final PDUReader pduReader; private SMPPServerSessionContext sessionContext = new SMPPServerSessionContext(this); private final ServerResponseHandler responseHandler = new ResponseHandlerImpl(); private ServerMessageReceiverListener messageReceiverListener; private ServerResponseDeliveryListener responseDeliveryListener; private final EnquireLinkSender enquireLinkSender; private BindRequestReceiver bindRequestReceiver = new BindRequestReceiver(responseHandler); public SMPPServerSession(Connection conn, SessionStateListener sessionStateListener, ServerMessageReceiverListener messageReceiverListener, ServerResponseDeliveryListener responseDeliveryListener, int pduProcessorDegree) { this(conn, sessionStateListener, messageReceiverListener, responseDeliveryListener, pduProcessorDegree, new SynchronizedPDUSender(new DefaultPDUSender()), new DefaultPDUReader()); } public SMPPServerSession(Connection conn, SessionStateListener sessionStateListener, ServerMessageReceiverListener messageReceiverListener, ServerResponseDeliveryListener responseDeliveryListener, int pduProcessorDegree, PDUSender pduSender, PDUReader pduReader) { super(pduSender); this.conn = conn; this.messageReceiverListener = messageReceiverListener; this.responseDeliveryListener = responseDeliveryListener; this.pduReader = pduReader; this.in = new DataInputStream(conn.getInputStream()); this.out = conn.getOutputStream(); enquireLinkSender = new EnquireLinkSender(); addSessionStateListener(new BoundStateListener()); addSessionStateListener(sessionStateListener); setPduProcessorDegree(pduProcessorDegree); sessionContext.open(); } /** * Wait for bind request. * * @param timeout is the timeout. * @return the {@link BindRequest}. * @throws IllegalStateException if this invocation of this method has been * made or invoke when state is not OPEN. * @throws TimeoutException if the timeout has been reach and * {@link SMPPServerSession} are no more valid because the * connection will be close automatically. */ public BindRequest waitForBind(long timeout) throws IllegalStateException, TimeoutException { if (getSessionState().equals(SessionState.OPEN)) { new PDUReaderWorker().start(); try { return bindRequestReceiver.waitForRequest(timeout); } catch (IllegalStateException e) { throw new IllegalStateException("Invocation of waitForBind() has been made", e); } catch (TimeoutException e) { close(); throw e; } } else { throw new IllegalStateException("waitForBind() should be invoked on OPEN state, actual state is " + SessionState.OPEN); } } private synchronized boolean isReadPdu() { SessionState sessionState = sessionContext.getSessionState(); return sessionState.isBound() || sessionState.equals(SessionState.OPEN); } public void deliverShortMessage(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocoId, byte priorityFlag, RegisteredDelivery registeredDelivery, DataCoding dataCoding, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { DeliverSmCommandTask task = new DeliverSmCommandTask(pduSender(), serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, protocoId, protocoId, registeredDelivery, dataCoding, shortMessage, optionalParameters); executeSendCommand(task, getTransactionTimer()); } /* (non-Javadoc) * @see org.jsmpp.session.ServerSession#alertNotification(int, org.jsmpp.bean.TypeOfNumber, org.jsmpp.bean.NumberingPlanIndicator, java.lang.String, org.jsmpp.bean.TypeOfNumber, org.jsmpp.bean.NumberingPlanIndicator, java.lang.String, org.jsmpp.bean.OptionalParameter[]) */ public void alertNotification(int sequenceNumber, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber esmeAddrTon, NumberingPlanIndicator esmeAddrNpi, String esmeAddr, OptionalParameter... optionalParameters) throws PDUStringException, IOException { pduSender().sendAlertNotification(connection().getOutputStream(), sequenceNumber, sourceAddrTon.value(), sourceAddrNpi.value(), sourceAddr, esmeAddrTon.value(), esmeAddrNpi.value(), esmeAddr, optionalParameters); } private MessageId fireAcceptSubmitSm(SubmitSm submitSm) throws ProcessRequestException { if (messageReceiverListener != null) { return messageReceiverListener.onAcceptSubmitSm(submitSm, this); } throw new ProcessRequestException("MessageReceveiverListener hasn't been set yet", SMPPConstant.STAT_ESME_RX_R_APPN); } private SubmitMultiResult fireAcceptSubmitMulti(SubmitMulti submitMulti) throws ProcessRequestException { if (messageReceiverListener != null) { return messageReceiverListener.onAcceptSubmitMulti(submitMulti, this); } throw new ProcessRequestException("MessageReceveiverListener hasn't been set yet", SMPPConstant.STAT_ESME_RX_R_APPN); } private QuerySmResult fireAcceptQuerySm(QuerySm querySm) throws ProcessRequestException { if (messageReceiverListener != null) { return messageReceiverListener.onAcceptQuerySm(querySm, this); } throw new ProcessRequestException("MessageReceveiverListener hasn't been set yet", SMPPConstant.STAT_ESME_RX_R_APPN); } private void fireAcceptReplaceSm(ReplaceSm replaceSm) throws ProcessRequestException { if (messageReceiverListener != null) { messageReceiverListener.onAcceptReplaceSm(replaceSm, this); } else { throw new ProcessRequestException("MessageReceveiverListener hasn't been set yet", SMPPConstant.STAT_ESME_RX_R_APPN); } } private void fireAcceptCancelSm(CancelSm cancelSm) throws ProcessRequestException { if (messageReceiverListener != null) { messageReceiverListener.onAcceptCancelSm(cancelSm, this); } else { throw new ProcessRequestException("MessageReceveiverListener hasn't been set yet", SMPPConstant.STAT_ESME_RX_R_APPN); } } private void fireSubmitSmRespSent(MessageId messageId) { if (responseDeliveryListener != null) { responseDeliveryListener.onSubmitSmRespSent(messageId, this); } } private void fireSubmitSmRespFailed(MessageId messageId, Exception cause) { if (responseDeliveryListener != null) { responseDeliveryListener.onSubmitSmRespError(messageId, cause, this); } } private void fireSubmitMultiRespSent(SubmitMultiResult submitMultiResult) { if (responseDeliveryListener != null) { responseDeliveryListener.onSubmitMultiRespSent( submitMultiResult, this); } } private void fireSubmitMultiRespSentError( SubmitMultiResult submitMultiResult, Exception cause) { if (responseDeliveryListener != null) { responseDeliveryListener.onSubmitMultiRespError( submitMultiResult, cause, this); } } @Override protected Connection connection() { return conn; } @Override protected AbstractSessionContext sessionContext() { return sessionContext; } @Override protected GenericMessageReceiverListener messageReceiverListener() { return messageReceiverListener; } public ServerMessageReceiverListener getMessageReceiverListener() { return messageReceiverListener; } public void setMessageReceiverListener( ServerMessageReceiverListener messageReceiverListener) { this.messageReceiverListener = messageReceiverListener; } public void setResponseDeliveryListener( ServerResponseDeliveryListener responseDeliveryListener) { this.responseDeliveryListener = responseDeliveryListener; } private class ResponseHandlerImpl implements ServerResponseHandler { public PendingResponse removeSentItem(int sequenceNumber) { return removePendingResponse(sequenceNumber); } public void notifyUnbonded() { sessionContext.unbound(); } public void sendEnquireLinkResp(int sequenceNumber) throws IOException { logger.debug("Sending enquire_link_resp"); pduSender().sendEnquireLinkResp(out, sequenceNumber); } public void sendGenerickNack(int commandStatus, int sequenceNumber) throws IOException { pduSender().sendGenericNack(out, commandStatus, sequenceNumber); } public void sendNegativeResponse(int originalCommandId, int commandStatus, int sequenceNumber) throws IOException { pduSender().sendHeader(out, originalCommandId | SMPPConstant.MASK_CID_RESP, commandStatus, sequenceNumber); } public void sendUnbindResp(int sequenceNumber) throws IOException { pduSender().sendUnbindResp(out, SMPPConstant.STAT_ESME_ROK, sequenceNumber); } public void sendBindResp(String systemId, BindType bindType, int sequenceNumber) throws IOException { sessionContext.bound(bindType); try { pduSender().sendBindResp(out, bindType.responseCommandId(), sequenceNumber, systemId); } catch (PDUStringException e) { logger.error("Failed sending bind response", e); // TODO uudashr: we have double checking when accept the bind request } } public void processBind(Bind bind) { bindRequestReceiver.notifyAcceptBind(bind); } public MessageId processSubmitSm(SubmitSm submitSm) throws ProcessRequestException { return fireAcceptSubmitSm(submitSm); } public void sendSubmitSmResponse(MessageId messageId, int sequenceNumber) throws IOException { try { pduSender().sendSubmitSmResp(out, sequenceNumber, messageId.getValue()); fireSubmitSmRespSent(messageId); } catch (PDUStringException e) { /* * There should be no PDUStringException thrown since creation * of MessageId should be save. */ logger.error("SYSTEM ERROR. Failed sending submitSmResp", e); fireSubmitSmRespFailed(messageId, e); } catch (IOException e) { fireSubmitSmRespFailed(messageId, e); throw e; } catch (RuntimeException e) { fireSubmitSmRespFailed(messageId, e); throw e; } } public SubmitMultiResult processSubmitMulti(SubmitMulti submitMulti) throws ProcessRequestException { return fireAcceptSubmitMulti(submitMulti); } public void sendSubmitMultiResponse( SubmitMultiResult submitMultiResult, int sequenceNumber) throws IOException { try { pduSender().sendSubmitMultiResp(out, sequenceNumber, submitMultiResult.getMessageId(), submitMultiResult.getUnsuccessDeliveries()); fireSubmitMultiRespSent(submitMultiResult); } catch (PDUStringException e) { /* * There should be no PDUStringException thrown since creation * of the response parameter has been validated. */ logger.error("SYSTEM ERROR. Failed sending submitMultiResp", e); fireSubmitMultiRespSentError(submitMultiResult, e); } catch (IOException e) { fireSubmitMultiRespSentError(submitMultiResult, e); throw e; } catch (RuntimeException e) { fireSubmitMultiRespSentError(submitMultiResult, e); throw e; } } public QuerySmResult processQuerySm(QuerySm querySm) throws ProcessRequestException { return fireAcceptQuerySm(querySm); } public void sendQuerySmResp(String messageId, String finalDate, MessageState messageState, byte errorCode, int sequenceNumber) throws IOException { try { pduSender().sendQuerySmResp(out, sequenceNumber, messageId, finalDate, messageState, errorCode); } catch (PDUStringException e) { /* * There should be no PDUStringException thrown since creation * of parsed messageId has been validated. */ logger.error("SYSTEM ERROR. Failed sending cancelSmResp", e); } } public DataSmResult processDataSm(DataSm dataSm) throws ProcessRequestException { return fireAcceptDataSm(dataSm); } // TODO uudashr: we can generalize this method public void sendDataSmResp(DataSmResult dataSmResult, int sequenceNumber) throws IOException { try { pduSender().sendDataSmResp(out, sequenceNumber, dataSmResult.getMessageId(), dataSmResult.getOptionalParameters()); } catch (PDUStringException e) { /* * There should be no PDUStringException thrown since creation * of MessageId should be save. */ logger.error("SYSTEM ERROR. Failed sending dataSmResp", e); } } public void processCancelSm(CancelSm cancelSm) throws ProcessRequestException { fireAcceptCancelSm(cancelSm); } public void sendCancelSmResp(int sequenceNumber) throws IOException { pduSender().sendCancelSmResp(out, sequenceNumber); } public void processReplaceSm(ReplaceSm replaceSm) throws ProcessRequestException { fireAcceptReplaceSm(replaceSm); } public void sendReplaceSmResp(int sequenceNumber) throws IOException { pduSender().sendReplaceSmResp(out, sequenceNumber); } } private class PDUReaderWorker extends Thread { private ExecutorService executorService = Executors.newFixedThreadPool(getPduProcessorDegree()); private Runnable onIOExceptionTask = new Runnable() { public void run() { close(); }; }; @Override public void run() { logger.info("Starting PDUReaderWorker with processor degree:{} ...", getPduProcessorDegree()); while (isReadPdu()) { readPDU(); } close(); executorService.shutdown(); logger.info("PDUReaderWorker stop"); } private void readPDU() { try { Command pduHeader = null; byte[] pdu = null; pduHeader = pduReader.readPDUHeader(in); pdu = pduReader.readPDU(in, pduHeader); PDUProcessServerTask task = new PDUProcessServerTask(pduHeader, pdu, sessionContext.getStateProcessor(), sessionContext, responseHandler, onIOExceptionTask); executorService.execute(task); } catch (InvalidCommandLengthException e) { logger.warn("Receive invalid command length", e); try { pduSender().sendGenericNack(out, SMPPConstant.STAT_ESME_RINVCMDLEN, 0); } catch (IOException ee) { logger.warn("Failed sending generic nack", ee); } unbindAndClose(); } catch (SocketTimeoutException e) { notifyNoActivity(); } catch (IOException e) { close(); } } /** * Notify for no activity. */ private void notifyNoActivity() { logger.debug("No activity notified"); enquireLinkSender.enquireLink(); } } private class EnquireLinkSender extends Thread { private final AtomicBoolean sendingEnquireLink = new AtomicBoolean(false); @Override public void run() { logger.info("Starting EnquireLinkSender"); while (isReadPdu()) { while (!sendingEnquireLink.compareAndSet(true, false) && isReadPdu()) { synchronized (sendingEnquireLink) { try { sendingEnquireLink.wait(500); } catch (InterruptedException e) { } } } if (!isReadPdu()) { break; } try { sendEnquireLink(); } catch (ResponseTimeoutException e) { close(); } catch (InvalidResponseException e) { // lets unbind gracefully unbindAndClose(); } catch (IOException e) { close(); } } logger.info("EnquireLinkSender stop"); } /** * This method will send enquire link asynchronously. */ public void enquireLink() { if (sendingEnquireLink.compareAndSet(false, true)) { synchronized (sendingEnquireLink) { sendingEnquireLink.notify(); } } } } private class BoundStateListener implements SessionStateListener { public void onStateChange(SessionState newState, SessionState oldState, Object source) { if (newState.isBound()) { enquireLinkSender.start(); } } } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/SMPPServerSessionContext.java000066400000000000000000000045551246113105100264310ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.extra.SessionState; import org.jsmpp.session.state.SMPPServerSessionState; /** * @author uudashr * */ public class SMPPServerSessionContext extends AbstractSessionContext { private SMPPServerSessionState stateProcessor = SMPPServerSessionState.CLOSED; private final SMPPServerSession smppServerSession; public SMPPServerSessionContext(SMPPServerSession smppServerSession) { this.smppServerSession = smppServerSession; } @Override protected void changeState(SessionState newState) { if (!stateProcessor.getSessionState().equals(newState)) { final SessionState oldState = stateProcessor.getSessionState(); // change the session state processor if (newState == SessionState.OPEN) { stateProcessor = SMPPServerSessionState.OPEN; } else if (newState == SessionState.BOUND_RX) { stateProcessor = SMPPServerSessionState.BOUND_RX; } else if (newState == SessionState.BOUND_TX) { stateProcessor = SMPPServerSessionState.BOUND_TX; } else if (newState == SessionState.BOUND_TRX) { stateProcessor = SMPPServerSessionState.BOUND_TRX; } else if (newState == SessionState.UNBOUND) { stateProcessor = SMPPServerSessionState.UNBOUND; } else if (newState == SessionState.CLOSED) { stateProcessor = SMPPServerSessionState.CLOSED; } fireStateChanged(newState, oldState, smppServerSession); } } public synchronized SMPPServerSessionState getStateProcessor() { return stateProcessor; } public synchronized SessionState getSessionState() { return stateProcessor.getSessionState(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/SMPPServerSessionListener.java000066400000000000000000000131741246113105100265670ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.net.SocketTimeoutException; import org.jsmpp.session.connection.Connection; import org.jsmpp.session.connection.ServerConnection; import org.jsmpp.session.connection.ServerConnectionFactory; import org.jsmpp.session.connection.socket.ServerSocketConnectionFactory; /** * This object responsible to for new SMPP Session request from ESME. It will * listen on specified port. * *
 * SMPPServerSession session = listener.accept();
 * BindRequest bindReq = session.waitForBind(5000);
 * 
 * if (checkPassword(bindReq)) {
 *     bindReq.accept("sys");
 * } else {
 *     bindReq.reject(SMPPConstant.STAT_ESME_RINVPASWD);
 * }
 * 
* *

* The listening trough getting the bind request should take less than session * initiation timer, otherwise if there is network open has been requested, ESME * will close the connection. Accepting the bind request should take less than * transaction timer or ESME will issued timeout. *

* * @author uudashr * */ public class SMPPServerSessionListener { private final int port; private final ServerConnection serverConn; private int initiationTimer = 5000; private int pduProcessorDegree = 3; private SessionStateListener sessionStateListener; private ServerMessageReceiverListener messageReceiverListener; private ServerResponseDeliveryListener responseDeliveryListener; public SMPPServerSessionListener(int port) throws IOException { this(port, new ServerSocketConnectionFactory()); } public SMPPServerSessionListener(int port, ServerConnectionFactory serverConnFactory) throws IOException { this.port = port; serverConn = serverConnFactory.listen(port); } public SMPPServerSessionListener(int port, int timeout, ServerConnectionFactory serverConnFactory) throws IOException { this.port = port; serverConn = serverConnFactory.listen(port, timeout); } public SMPPServerSessionListener(int port, int timeout, int backlog, ServerConnectionFactory serverConnFactory) throws IOException { this.port = port; serverConn = serverConnFactory.listen(port, timeout, backlog); } public int getTimeout(int timeout) throws IOException { return serverConn.getSoTimeout(); } /** * Timeout listening. When timeout reach and connection request didn't * arrive then {@link SocketTimeoutException} will be thrown but the * listener still valid. * * @param timeout * @throws IOException */ public void setTimeout(int timeout) throws IOException { serverConn.setSoTimeout(timeout); } public void setPduProcessorDegree(int pduProcessorDegree) { this.pduProcessorDegree = pduProcessorDegree; } public int getPduProcessorDegree() { return pduProcessorDegree; } public int getPort() { return port; } public int getInitiationTimer() { return initiationTimer; } public void setInitiationTimer(int initiationTimer) { this.initiationTimer = initiationTimer; } public SessionStateListener getSessionStateListener() { return sessionStateListener; } public void setSessionStateListener( SessionStateListener sessionStateListener) { this.sessionStateListener = sessionStateListener; } public ServerMessageReceiverListener getMessageReceiverListener() { return messageReceiverListener; } public void setMessageReceiverListener( ServerMessageReceiverListener messageReceiverListener) { this.messageReceiverListener = messageReceiverListener; } public void setResponseDeliveryListener( ServerResponseDeliveryListener responseDeliveryListener) { this.responseDeliveryListener = responseDeliveryListener; } /** * Accept session request from client. The session state is still OPEN. To * communicate with ESME properly binding request should be accepted. * *
     * SMPPServerSession session = listener.accept();
     * BindRequest bindReq = session.waitForBind(5000);
     * 
     * if (checkPassword(bindReq)) {
     *     bindReq.accept("sys");
     * } else {
     *     bindReq.reject(SMPPConstant.STAT_ESME_RINVPASWD);
     * }
     * 
* * @return the accepted {@link SMPPServerSession}. * @throws SocketTimeoutException if timeout reach with no session accepted. * @throws IOException if there is an IO error occur. * @see SMPPServerSession * @see BindRequest */ public SMPPServerSession accept() throws IOException { Connection conn = serverConn.accept(); conn.setSoTimeout(initiationTimer); return new SMPPServerSession(conn, sessionStateListener, messageReceiverListener, responseDeliveryListener, pduProcessorDegree); } public void close() throws IOException { serverConn.close(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/SMPPSession.java000066400000000000000000000643771246113105100237050ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.SocketTimeoutException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import org.jsmpp.DefaultPDUReader; import org.jsmpp.DefaultPDUSender; import org.jsmpp.InvalidCommandLengthException; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.PDUReader; import org.jsmpp.PDUSender; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.SynchronizedPDUSender; import org.jsmpp.bean.Address; import org.jsmpp.bean.AlertNotification; import org.jsmpp.bean.BindResp; import org.jsmpp.bean.BindType; import org.jsmpp.bean.Command; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.DataSm; import org.jsmpp.bean.DeliverSm; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.InterfaceVersion; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.QuerySmResp; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.ReplaceIfPresentFlag; import org.jsmpp.bean.SubmitMultiResp; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.SubmitSmResp; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.PendingResponse; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.extra.SessionState; import org.jsmpp.session.connection.Connection; import org.jsmpp.session.connection.ConnectionFactory; import org.jsmpp.session.connection.socket.SocketConnectionFactory; import org.jsmpp.util.DefaultComposer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is an object that used to communicate with SMPP Server or SMSC. It hide * all un-needed SMPP operation that might harm if the user code use it such as : *
    *
  • DELIVER_SM_RESP, should be called only as response to DELIVER_SM
  • *
  • UNBIND_RESP, should be called only as response to UNBIND_RESP
  • *
  • DATA_SM_RESP, should be called only as response to DATA_SM
  • *
  • ENQUIRE_LINK_RESP, should be called only as response to ENQUIRE_LINK
  • *
  • GENERIC_NACK, should be called only as response to GENERIC_NACK
  • *
* * All SMPP operation (request-response) is blocking, for an example: SUBMIT_SM * will be blocked until SUBMIT_SM_RESP received or timeout. This looks like * synchronous communication, but the {@link SMPPClient} implementation give * ability to the asynchronous way by executing the SUBMIT_SM operation parallel * on a different thread. The very simple implementation by using Thread pool, * {@link ExecutorService} will do. * * To receive the incoming message such as DELIVER_SM or DATA_SM will be managed * by internal thread. User code only have to set listener * {@link MessageReceiverListener}. * * @author uudashr * */ public class SMPPSession extends AbstractSession implements ClientSession { private static final Logger logger = LoggerFactory.getLogger(SMPPSession.class); /* Utility */ private final PDUReader pduReader; /* Connection */ private final ConnectionFactory connFactory; private Connection conn; private DataInputStream in; private OutputStream out; private final ResponseHandler responseHandler = new ResponseHandlerImpl(); private MessageReceiverListener messageReceiverListener; private BoundSessionStateListener sessionStateListener = new BoundSessionStateListener(); private SMPPSessionContext sessionContext = new SMPPSessionContext(this, sessionStateListener); private EnquireLinkSender enquireLinkSender; /** * Default constructor of {@link SMPPSession}. The next action might be * connect and bind to a destination message center. * * @see #connectAndBind(String, int, BindType, String, String, String, TypeOfNumber, NumberingPlanIndicator, String) */ public SMPPSession() { this(new SynchronizedPDUSender(new DefaultPDUSender(new DefaultComposer())), new DefaultPDUReader(), SocketConnectionFactory.getInstance()); } public SMPPSession(PDUSender pduSender, PDUReader pduReader, ConnectionFactory connFactory) { super(pduSender); this.pduReader = pduReader; this.connFactory = connFactory; addSessionStateListener(new BoundSessionStateListener()); } public SMPPSession(String host, int port, BindParameter bindParam, PDUSender pduSender, PDUReader pduReader, ConnectionFactory connFactory) throws IOException { this(pduSender, pduReader, connFactory); connectAndBind(host, port, bindParam); } public SMPPSession(String host, int port, BindParameter bindParam) throws IOException { this(); connectAndBind(host, port, bindParam); } /** * Open connection and bind immediately. * * @param host is the SMSC host address. * @param port is the SMSC listen port. * @param bindType is the bind type. * @param systemId is the system id. * @param password is the password. * @param systemType is the system type. * @param addrTon is the address TON. * @param addrNpi is the address NPI. * @param addressRange is the address range. * @throws IOException if there is an IO error found. */ public void connectAndBind(String host, int port, BindType bindType, String systemId, String password, String systemType, TypeOfNumber addrTon, NumberingPlanIndicator addrNpi, String addressRange) throws IOException { connectAndBind(host, port, new BindParameter(bindType, systemId, password, systemType, addrTon, addrNpi, addressRange), 60000); } /** * Open connection and bind immediately with specified timeout. The default * timeout is 1 minutes. * * @param host is the SMSC host address. * @param port is the SMSC listen port. * @param bindType is the bind type. * @param systemId is the system id. * @param password is the password. * @param systemType is the system type. * @param addrTon is the address TON. * @param addrNpi is the address NPI. * @param addressRange is the address range. * @param timeout is the timeout. * @throws IOException if there is an IO error found. */ public void connectAndBind(String host, int port, BindType bindType, String systemId, String password, String systemType, TypeOfNumber addrTon, NumberingPlanIndicator addrNpi, String addressRange, long timeout) throws IOException { connectAndBind(host, port, new BindParameter(bindType, systemId, password, systemType, addrTon, addrNpi, addressRange), timeout); } /** * Open connection and bind immediately. * * @param host is the SMSC host address. * @param port is the SMSC listen port. * @param bindParam is the bind parameters. * @return the SMSC system id. * @throws IOException if there is an IO error found. */ public String connectAndBind(String host, int port, BindParameter bindParam) throws IOException { return connectAndBind(host, port, bindParam, 60000); } /** * Open connection and bind immediately. * * @param host is the SMSC host address. * @param port is the SMSC listen port. * @param bindParam is the bind parameters. * @param timeout is the timeout. * @return the SMSC system id. * @throws IOException if there is an IO error found. */ public String connectAndBind(String host, int port, BindParameter bindParam, long timeout) throws IOException { logger.debug("Connect and bind to {} port {}", host, port); if (sequence().currentValue() != 1) { throw new IOException("Failed connecting"); } conn = connFactory.createConnection(host, port); logger.info("Connected"); conn.setSoTimeout(getEnquireLinkTimer()); sessionContext.open(); try { in = new DataInputStream(conn.getInputStream()); out = conn.getOutputStream(); new PDUReaderWorker().start(); String smscSystemId = sendBind(bindParam.getBindType(), bindParam.getSystemId(), bindParam.getPassword(), bindParam.getSystemType(), InterfaceVersion.IF_34, bindParam.getAddrTon(), bindParam.getAddrNpi(), bindParam.getAddressRange(), timeout); sessionContext.bound(bindParam.getBindType()); enquireLinkSender = new EnquireLinkSender(); enquireLinkSender.start(); return smscSystemId; } catch (PDUException e) { logger.error("Failed sending bind command", e); throw new IOException("Failed sending bind since some string parameter area invalid : " + e.getMessage()); } catch (NegativeResponseException e) { String message = "Receive negative bind response"; logger.error(message, e); close(); throw new IOException(message + ": " + e.getMessage()); } catch (InvalidResponseException e) { String message = "Receive invalid response of bind"; logger.error(message, e); close(); throw new IOException(message + ": " + e.getMessage()); } catch (ResponseTimeoutException e) { String message = "Waiting bind response take time to long"; logger.error(message, e); close(); throw new IOException(message + ": " + e.getMessage()); } catch (IOException e) { logger.error("IO Error occur", e); close(); throw e; } } /** * Sending bind. * * @param bindType is the bind type. * @param systemId is the system id. * @param password is the password. * @param systemTypeis the system type. * @param interfaceVersion is the interface version. * @param addrTon is the address TON. * @param addrNpi is the address NPI. * @param addressRange is the address range. * @param timeout is the max time waiting for bind response. * @return SMSC system id. * @throws PDUException if we enter invalid bind parameter(s). * @throws ResponseTimeoutException if there is no valid response after defined millisecond. * @throws InvalidResponseException if there is invalid response found. * @throws NegativeResponseException if we receive negative response. * @throws IOException if there is an IO error occur. */ private String sendBind(BindType bindType, String systemId, String password, String systemType, InterfaceVersion interfaceVersion, TypeOfNumber addrTon, NumberingPlanIndicator addrNpi, String addressRange, long timeout) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { BindCommandTask task = new BindCommandTask(pduSender(), bindType, systemId, password, systemType, interfaceVersion, addrTon, addrNpi, addressRange); BindResp resp = (BindResp)executeSendCommand(task, timeout); return resp.getSystemId(); } /* (non-Javadoc) * @see org.jsmpp.session.ClientSession#submitShortMessage(java.lang.String, org.jsmpp.bean.TypeOfNumber, org.jsmpp.bean.NumberingPlanIndicator, java.lang.String, org.jsmpp.bean.TypeOfNumber, org.jsmpp.bean.NumberingPlanIndicator, java.lang.String, org.jsmpp.bean.ESMClass, byte, byte, java.lang.String, java.lang.String, org.jsmpp.bean.RegisteredDelivery, byte, org.jsmpp.bean.DataCoding, byte, byte[], org.jsmpp.bean.OptionalParameter[]) */ public String submitShortMessage(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { SubmitSmCommandTask submitSmTask = new SubmitSmCommandTask( pduSender(), serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, protocolId, priorityFlag, scheduleDeliveryTime, validityPeriod, registeredDelivery, replaceIfPresentFlag, dataCoding, smDefaultMsgId, shortMessage, optionalParameters); SubmitSmResp resp = (SubmitSmResp)executeSendCommand(submitSmTask, getTransactionTimer()); return resp.getMessageId(); } /* (non-Javadoc) * @see org.jsmpp.session.ClientSession#submitMultiple(java.lang.String, org.jsmpp.bean.TypeOfNumber, org.jsmpp.bean.NumberingPlanIndicator, java.lang.String, org.jsmpp.bean.Address[], org.jsmpp.bean.ESMClass, byte, byte, java.lang.String, java.lang.String, org.jsmpp.bean.RegisteredDelivery, org.jsmpp.bean.ReplaceIfPresentFlag, org.jsmpp.bean.DataCoding, byte, byte[], org.jsmpp.bean.OptionalParameter[]) */ public SubmitMultiResult submitMultiple(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, Address[] destinationAddresses, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, ReplaceIfPresentFlag replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter[] optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { SubmitMultiCommandTask task = new SubmitMultiCommandTask(pduSender(), serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destinationAddresses, esmClass, protocolId, priorityFlag, scheduleDeliveryTime, validityPeriod, registeredDelivery, replaceIfPresentFlag, dataCoding, smDefaultMsgId, shortMessage, optionalParameters); SubmitMultiResp resp = (SubmitMultiResp)executeSendCommand(task, getTransactionTimer()); return new SubmitMultiResult(resp.getMessageId(), resp .getUnsuccessSmes()); } /* (non-Javadoc) * @see org.jsmpp.session.ClientSession#queryShortMessage(java.lang.String, org.jsmpp.bean.TypeOfNumber, org.jsmpp.bean.NumberingPlanIndicator, java.lang.String) */ public QuerySmResult queryShortMessage(String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { QuerySmCommandTask task = new QuerySmCommandTask(pduSender(), messageId, sourceAddrTon, sourceAddrNpi, sourceAddr); QuerySmResp resp = (QuerySmResp)executeSendCommand(task, getTransactionTimer()); if (resp.getMessageId().equals(messageId)) { return new QuerySmResult(resp.getFinalDate(), resp .getMessageState(), resp.getErrorCode()); } else { // message id requested not same as the returned throw new InvalidResponseException( "Requested message_id doesn't match with the result"); } } /* (non-Javadoc) * @see org.jsmpp.session.ClientSession#replaceShortMessage(java.lang.String, org.jsmpp.bean.TypeOfNumber, org.jsmpp.bean.NumberingPlanIndicator, java.lang.String, java.lang.String, java.lang.String, org.jsmpp.bean.RegisteredDelivery, byte, byte[]) */ public void replaceShortMessage(String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte smDefaultMsgId, byte[] shortMessage) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { ReplaceSmCommandTask replaceSmTask = new ReplaceSmCommandTask( pduSender(), messageId, sourceAddrTon, sourceAddrNpi, sourceAddr, scheduleDeliveryTime, validityPeriod, registeredDelivery, smDefaultMsgId, shortMessage); executeSendCommand(replaceSmTask, getTransactionTimer()); } /* (non-Javadoc) * @see org.jsmpp.session.ClientSession#cancelShortMessage(java.lang.String, java.lang.String, org.jsmpp.bean.TypeOfNumber, org.jsmpp.bean.NumberingPlanIndicator, java.lang.String, org.jsmpp.bean.TypeOfNumber, org.jsmpp.bean.NumberingPlanIndicator, java.lang.String) */ public void cancelShortMessage(String serviceType, String messageId, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddress) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException { CancelSmCommandTask task = new CancelSmCommandTask(pduSender(), serviceType, messageId, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddress); executeSendCommand(task, getTransactionTimer()); } public MessageReceiverListener getMessageReceiverListener() { return messageReceiverListener; } public void setMessageReceiverListener( MessageReceiverListener messageReceiverListener) { this.messageReceiverListener = messageReceiverListener; } @Override protected Connection connection() { return conn; } @Override protected AbstractSessionContext sessionContext() { return sessionContext; } @Override protected GenericMessageReceiverListener messageReceiverListener() { return messageReceiverListener; } private synchronized boolean isReadPdu() { return sessionContext.getSessionState().isBound() || sessionContext.getSessionState().equals(SessionState.OPEN); } @Override protected void finalize() throws Throwable { close(); } private void fireAcceptDeliverSm(DeliverSm deliverSm) throws ProcessRequestException { if (messageReceiverListener != null) { messageReceiverListener.onAcceptDeliverSm(deliverSm); } else { logger.warn("Receive deliver_sm but MessageReceiverListener is null. Short message = " + new String(deliverSm.getShortMessage())); } } private void fireAcceptAlertNotification(AlertNotification alertNotification) { if (messageReceiverListener != null) { messageReceiverListener.onAcceptAlertNotification(alertNotification); } else { logger.warn("Receive alert_notification but MessageReceiverListener is null"); } } private class ResponseHandlerImpl implements ResponseHandler { public void processDeliverSm(DeliverSm deliverSm) throws ProcessRequestException { fireAcceptDeliverSm(deliverSm); } public DataSmResult processDataSm(DataSm dataSm) throws ProcessRequestException { return fireAcceptDataSm(dataSm); } public void processAlertNotification(AlertNotification alertNotification) { fireAcceptAlertNotification(alertNotification); } public void sendDataSmResp(DataSmResult dataSmResult, int sequenceNumber) throws IOException { try { pduSender().sendDataSmResp(out, sequenceNumber, dataSmResult.getMessageId(), dataSmResult.getOptionalParameters()); } catch (PDUStringException e) { /* * There should be no PDUStringException thrown since creation * of MessageId should be save. */ logger.error("SYSTEM ERROR. Failed sending dataSmResp", e); } } public PendingResponse removeSentItem(int sequenceNumber) { return removePendingResponse(sequenceNumber); } public void notifyUnbonded() { sessionContext.unbound(); } public void sendDeliverSmResp(int sequenceNumber) throws IOException { pduSender().sendDeliverSmResp(out, sequenceNumber); logger.debug("deliver_sm_resp with seq_number " + sequenceNumber + " has been sent"); } public void sendEnquireLinkResp(int sequenceNumber) throws IOException { logger.debug("Sending enquire_link_resp"); pduSender().sendEnquireLinkResp(out, sequenceNumber); } public void sendGenerickNack(int commandStatus, int sequenceNumber) throws IOException { pduSender().sendGenericNack(out, commandStatus, sequenceNumber); } public void sendNegativeResponse(int originalCommandId, int commandStatus, int sequenceNumber) throws IOException { pduSender().sendHeader(out, originalCommandId | SMPPConstant.MASK_CID_RESP, commandStatus, sequenceNumber); } public void sendUnbindResp(int sequenceNumber) throws IOException { pduSender().sendUnbindResp(out, SMPPConstant.STAT_ESME_ROK, sequenceNumber); } } /** * Worker to read the PDU. * * @author uudashr * */ private class PDUReaderWorker extends Thread { private ExecutorService executorService = Executors.newFixedThreadPool(getPduProcessorDegree()); private Runnable onIOExceptionTask = new Runnable() { public void run() { close(); }; }; @Override public void run() { logger.info("Starting PDUReaderWorker with processor degree:{} ...", getPduProcessorDegree()); while (isReadPdu()) { readPDU(); } close(); executorService.shutdown(); logger.info("PDUReaderWorker stop"); } private void readPDU() { try { Command pduHeader = null; byte[] pdu = null; pduHeader = pduReader.readPDUHeader(in); pdu = pduReader.readPDU(in, pduHeader); /* * When the processing PDU is need user interaction via event, * the code on event might take non-short time, so we need to * process it concurrently. */ PDUProcessTask task = new PDUProcessTask(pduHeader, pdu, sessionContext.getStateProcessor(), responseHandler, sessionContext, onIOExceptionTask); executorService.execute(task); } catch (InvalidCommandLengthException e) { logger.warn("Receive invalid command length", e); try { pduSender().sendGenericNack(out, SMPPConstant.STAT_ESME_RINVCMDLEN, 0); } catch (IOException ee) { logger.warn("Failed sending generic nack", ee); } unbindAndClose(); } catch (SocketTimeoutException e) { notifyNoActivity(); } catch (IOException e) { close(); } } /** * Notify for no activity. */ private void notifyNoActivity() { logger.debug("No activity notified"); if (sessionContext().getSessionState().isBound()) { enquireLinkSender.enquireLink(); } } } private class EnquireLinkSender extends Thread { private final AtomicBoolean sendingEnquireLink = new AtomicBoolean(false); @Override public void run() { logger.info("Starting EnquireLinkSender"); while (isReadPdu()) { while (!sendingEnquireLink.compareAndSet(true, false) && isReadPdu()) { synchronized (sendingEnquireLink) { try { sendingEnquireLink.wait(500); } catch (InterruptedException e) { } } } if (!isReadPdu()) { break; } try { sendEnquireLink(); } catch (ResponseTimeoutException e) { close(); } catch (InvalidResponseException e) { // lets unbind gracefully unbindAndClose(); } catch (IOException e) { close(); } } logger.info("EnquireLinkSender stop"); } /** * This method will send enquire link asynchronously. */ public void enquireLink() { if (sendingEnquireLink.compareAndSet(false, true)) { logger.debug("Sending enquire link notify"); synchronized (sendingEnquireLink) { sendingEnquireLink.notify(); } } else { logger.debug("Not sending enquire link notify"); } } } /** * Session state listener for internal class use. * * @author uudashr * */ private class BoundSessionStateListener implements SessionStateListener { public void onStateChange(SessionState newState, SessionState oldState, Object source) { /* * We need to set SO_TIMEOUT to sessionTimer so when timeout occur, * a SocketTimeoutException will be raised. When Exception raised we * can send an enquireLinkCommand. */ if (newState.isBound()) { try { conn.setSoTimeout(getEnquireLinkTimer()); } catch (IOException e) { logger.error("Failed setting so_timeout for session timer", e); } } } } }jsmpp-2.1.2/src/main/java/org/jsmpp/session/SMPPSessionContext.java000066400000000000000000000045271246113105100252410ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.extra.SessionState; import org.jsmpp.session.state.SMPPSessionState; /** * @author uudashr * */ public class SMPPSessionContext extends AbstractSessionContext { private final SMPPSession smppSession; private SMPPSessionState stateProcessor = SMPPSessionState.CLOSED; public SMPPSessionContext(SMPPSession smppSession, SessionStateListener sessionStateListener) { super(sessionStateListener); this.smppSession = smppSession; } public synchronized SMPPSessionState getStateProcessor() { return stateProcessor; } public synchronized SessionState getSessionState() { return stateProcessor.getSessionState(); } @Override protected void changeState(SessionState newState) { if (!stateProcessor.getSessionState().equals(newState)) { final SessionState oldState = stateProcessor.getSessionState(); // change the session state processor if (newState == SessionState.OPEN) { stateProcessor = SMPPSessionState.OPEN; } else if (newState == SessionState.BOUND_RX) { stateProcessor = SMPPSessionState.BOUND_RX; } else if (newState == SessionState.BOUND_TX) { stateProcessor = SMPPSessionState.BOUND_TX; } else if (newState == SessionState.BOUND_TRX) { stateProcessor = SMPPSessionState.BOUND_TRX; } else if (newState == SessionState.UNBOUND) { stateProcessor = SMPPSessionState.UNBOUND; } else if (newState == SessionState.CLOSED) { stateProcessor = SMPPSessionState.CLOSED; } fireStateChanged(newState, oldState, smppSession); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/SendCommandTask.java000066400000000000000000000024731246113105100245620ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.PDUException; /** * Task for sending SMPP command. * * @author uudashr * */ public interface SendCommandTask { /** * Executing the task. * * @param out is the output stream. * @param sequenceNumber is the sequence number. * @throws PDUException if there is an invalid PDU parameter found. * @throws IOException if there is an IO error found. */ void executeTask(OutputStream out, int sequenceNumber) throws PDUException, IOException; /** * It should be like submit_sm, deliver_sm, query_sm, data_sm, etc. * * @return the command name. */ String getCommandName(); } jsmpp-2.1.2/src/main/java/org/jsmpp/session/ServerMessageReceiverListener.java000066400000000000000000000031431246113105100275100ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.bean.CancelSm; import org.jsmpp.bean.QuerySm; import org.jsmpp.bean.ReplaceSm; import org.jsmpp.bean.SubmitMulti; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.SubmitSm; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.util.MessageId; /** * @author uudashr * */ public interface ServerMessageReceiverListener extends GenericMessageReceiverListener { MessageId onAcceptSubmitSm(SubmitSm submitSm, SMPPServerSession source) throws ProcessRequestException; SubmitMultiResult onAcceptSubmitMulti(SubmitMulti submitMulti, SMPPServerSession source) throws ProcessRequestException; QuerySmResult onAcceptQuerySm(QuerySm querySm, SMPPServerSession source) throws ProcessRequestException; void onAcceptReplaceSm(ReplaceSm replaceSm, SMPPServerSession source) throws ProcessRequestException; void onAcceptCancelSm(CancelSm cancelSm, SMPPServerSession source) throws ProcessRequestException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/ServerResponseDeliveryAdapter.java000066400000000000000000000046221246113105100275370ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.util.MessageId; /** * It's abstract adapter class that receive event of response delivery, an * implementation of {@link ServerResponseDeliveryListener}. *

* This is alternative from implementing {@link ServerResponseDeliveryListener}. * User only have to create subclass of this class and doesn't have to implement * all method declared on {@link ServerResponseDeliveryListener}. *

* * @author uudashr * */ public abstract class ServerResponseDeliveryAdapter implements ServerResponseDeliveryListener { /* (non-Javadoc) * @see org.jsmpp.session.ServerResponseDeliveryListener#onSubmitSmResponseSent(org.jsmpp.util.MessageId, org.jsmpp.session.SMPPServerSession) */ public void onSubmitSmRespSent(MessageId messageId, SMPPServerSession source) {} /* (non-Javadoc) * @see org.jsmpp.session.ServerResponseDeliveryListener#onSubmitSmResponseError(org.jsmpp.util.MessageId, java.lang.Exception, org.jsmpp.session.SMPPServerSession) */ public void onSubmitSmRespError(MessageId messageId, Exception e, SMPPServerSession source) {} /* (non-Javadoc) * @see org.jsmpp.session.ServerResponseDeliveryListener#onSubmitMultiResponseSent(org.jsmpp.bean.SubmitMultiResult, org.jsmpp.session.SMPPServerSession) */ public void onSubmitMultiRespSent(SubmitMultiResult submitMultiResult, SMPPServerSession source) {} /* (non-Javadoc) * @see org.jsmpp.session.ServerResponseDeliveryListener#onSubmitMultiResposnseError(org.jsmpp.bean.SubmitMultiResult, java.lang.Exception, org.jsmpp.session.SMPPServerSession) */ public void onSubmitMultiRespError( SubmitMultiResult submitMultiResult, Exception e, SMPPServerSession source) {} } jsmpp-2.1.2/src/main/java/org/jsmpp/session/ServerResponseDeliveryListener.java000066400000000000000000000053331246113105100277440ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.util.MessageId; /** * This is listener will be used by {@link SMPPServerSession} to notify a user * when a response has been sent. *

* Some of user code might be implemented on {@link SMPPServerSession} is *

    *
  • {@link ServerMessageReceiverListener#onAcceptSubmitSm(org.jsmpp.bean.SubmitSm, SMPPServerSession)}
  • *
  • {@link ServerMessageReceiverListener#onAcceptSubmitMulti(org.jsmpp.bean.SubmitMulti, SMPPServerSession)}
  • *
* Both implementation of those method might take long time. *

* @author uudashr */ public interface ServerResponseDeliveryListener { /** * This event raised when submit_sm_resp delivery is succeed. * * @param messageId is the message id that will be sent to client as * response. * @param source is the session who handle this response. */ void onSubmitSmRespSent(MessageId messageId, SMPPServerSession source); /** * This event raised when submit_sm_resp delivery is failed. * * @param messageId is the message id that will be sent to client as * response. * @param cause is the failure cause. * @param source is the session who handle this response. */ void onSubmitSmRespError(MessageId messageId, Exception cause, SMPPServerSession source); /** * This event raised when submit_multi_resp delivery is succeed. * * @param submitMultiResult is the result that will be sent to client as * response. * @param source is the session who handle this response. */ void onSubmitMultiRespSent(SubmitMultiResult submitMultiResult, SMPPServerSession source); /** * This event raised when submit_multi_resp delivery is failed. * * @param submitMultiResult is the result that will be sent to client as * response. * @param cause is the failure cause. * @param source is the session who handle this response. */ void onSubmitMultiRespError(SubmitMultiResult submitMultiResult, Exception cause, SMPPServerSession source); } jsmpp-2.1.2/src/main/java/org/jsmpp/session/ServerResponseHandler.java000066400000000000000000000043031246113105100260240ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.bean.Bind; import org.jsmpp.bean.BindType; import org.jsmpp.bean.CancelSm; import org.jsmpp.bean.MessageState; import org.jsmpp.bean.QuerySm; import org.jsmpp.bean.ReplaceSm; import org.jsmpp.bean.SubmitMulti; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.SubmitSm; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.util.MessageId; /** * @author uudashr * */ public interface ServerResponseHandler extends BaseResponseHandler { void sendBindResp(String systemId, BindType bindType, int sequenceNumber) throws IOException; void sendSubmitSmResponse(MessageId messageId, int sequenceNumber) throws IOException; void processBind(Bind bind); MessageId processSubmitSm(SubmitSm submitSm) throws ProcessRequestException; SubmitMultiResult processSubmitMulti(SubmitMulti submitMulti) throws ProcessRequestException; void sendSubmitMultiResponse(SubmitMultiResult submiitMultiResult, int sequenceNumber) throws IOException; QuerySmResult processQuerySm(QuerySm querySm) throws ProcessRequestException; void sendQuerySmResp(String messageId, String finalDate, MessageState messageState, byte errorCode, int sequenceNumber) throws IOException; void processCancelSm(CancelSm cancelSm) throws ProcessRequestException; void sendCancelSmResp(int sequenceNumber) throws IOException; void processReplaceSm(ReplaceSm replaceSm) throws ProcessRequestException; void sendReplaceSmResp(int sequenceNumber) throws IOException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/ServerSession.java000066400000000000000000000111751246113105100243600ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.PDUStringException; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; /** * This interface provides all operation that the server session can do. It * doesn't distinct the operation of specific session type (Transmitter, * Receiver) it's just like Transceiver. The distinction might should be * recognized in a different way, such as by user code when they are accepting * bind request or by throwing exception when invoking illegal operation. * * @author uudashr * */ public interface ServerSession { /** * Submit a short message to specified destination address (ESME). This method will * blocks until response received or timeout reached. This method simplify * operations of sending DELIVER_SM command and receiving the DELIVER_SM_RESP. * * @param serviceType is the service_type. * @param sourceAddrTon is the source_addr_ton. * @param sourceAddrNpi is the source_addr_npi. * @param sourceAddr is the source_addr. * @param destAddrTon is the dest_addr_ton. * @param destAddrNpi is the dest_addr_npi. * @param destinationAddr is the destination_addr. * @param esmClass is the esm_class. * @param protocoId is the protocol_id. * @param priorityFlag is the priority_flag. * @param registeredDelivery is the registered_delivery. * @param dataCoding is the data_coding. * @param shortMessage is the short_message. * @param optionalParameters is the optional parameters. * @throws PDUException if there is invalid PDU parameter found. * @throws ResponseTimeoutException if timeout has been reach. * @throws InvalidResponseException if response is invalid. * @throws NegativeResponseException if negative response received. * @throws IOException if there is an I/O error found. */ void deliverShortMessage(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocoId, byte priorityFlag, RegisteredDelivery registeredDelivery, DataCoding dataCoding, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; /** * Send alert notification to ESME in order to notify the particular mobile * subscriber has become available. * * @param sequenceNumber is the sequence_number. * @param sourceAddrTon is the source_addr_ton. * @param sourceAddrNpi is the source_addr_npi. * @param sourceAddr is the source_addr. * @param esmeAddrTon is the esm_addr_ton. * @param esmeAddrNpi is the esme_addr_npi. * @param esmeAddr is the esme_addr. * @param optionalParameters is the optional parameters. * @throws PDUStringException if there is invalid string found. * @throws ResponseTimeoutException if timeout has been reach. * @throws InvalidResponseException if response is invalid. * @throws NegativeResponseException if negative response received. * @throws IOException if there is an I/O error found. */ void alertNotification(int sequenceNumber, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber esmeAddrTon, NumberingPlanIndicator esmeAddrNpi, String esmeAddr, OptionalParameter... optionalParameters) throws PDUStringException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/Session.java000066400000000000000000000110511246113105100231620ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.extra.SessionState; /** * Session describe all abilities of the session. Each created session will be * identified with session id and has a state (open, bound, unbound, closed). * Every changes of state will be notified and the event can be captured by * implementing {@link SessionStateListener} and register it to a session * {@link #addSessionStateListener(SessionStateListener)}. * *

* Commonly, every SMPP request has a response. The maximum waiting time can be * configured as transaction timer. *

    *
  • {@link #setTransactionTimer(long)}
  • *
  • {@link #getTransactionTimer()}
  • *
*

* *

* To terminate the communication with the Message Center gracefully, invoke * {@link #unbindAndClose()}. It will send UNBIND command and close the * connection. This method will wait the UNIBIND_RESP but, negative response * will be acceptable and closing connection will be done immediately. *

* * @see SessionState * * @author uudashr * */ public interface Session { /** * Sending a short message like SUBMIT_SM. This method will blocks until * response received or timeout reached. This method simplify operation of * sending DATA_SM and receiving DATA_SM_RESP. * * @param serviceType is the service_type. * @param sourceAddrTon is the source_addr_ton. * @param sourceAddrNpi is the source_addr_npi. * @param sourceAddr is the source_addr. * @param destAddrTon is the dest_addr_ton. * @param destAddrNpi is the dest_addr_npi. * @param destinationAddr is the destination_address. * @param esmClass is the esm_class. * @param registeredDelivery is the registered_delivery. * @param dataCoding is the data_coding. * @param optionalParameters is the optional parameters. * @return the response/result of DATA_SM. * @throws PDUException if there is invalid PDU parameter found. * @throws ResponseTimeoutException if timeout has been reached. * @throws InvalidResponseException if response is invalid. * @throws NegativeResponseException if negative response received. * @throws IOException if there is an I/O error found. */ DataSmResult dataShortMessage(String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, RegisteredDelivery registeredDelivery, DataCoding dataCoding, OptionalParameter... optionalParameters) throws PDUException, ResponseTimeoutException, InvalidResponseException, NegativeResponseException, IOException; /** * Get session id. * * @return the session id. */ String getSessionId(); void setEnquireLinkTimer(int enquireLinkTimer); int getEnquireLinkTimer(); void setTransactionTimer(long transactionTimer); long getTransactionTimer(); SessionState getSessionState(); void addSessionStateListener(SessionStateListener l); void removeSessionStateListener(SessionStateListener l); /** * Get the last reading valid PDU from remote host. * * @return the last reading valid PDU from remote host. */ long getLastActivityTimestamp(); /** * Forced close connection without sending UNBIND command to Message Center. */ void close(); /** * Sending UNBIND and close connection immediately. */ void unbindAndClose(); } jsmpp-2.1.2/src/main/java/org/jsmpp/session/SessionContext.java000066400000000000000000000027131246113105100245340ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.bean.BindType; import org.jsmpp.extra.SessionState; /** * Context defined session life cycle.
* OPEN -> BOUND_TX | BOUND_RX | BOUND_TRX -> UNBOUND -> CLOSE. * * @author uudashr * */ public interface SessionContext extends ActivityNotifier { /** * Change state to open. */ void open(); /** * Change state to bound state. * @param bindType */ void bound(BindType bindType); /** * Change state to unbound. */ void unbound(); /** * Change state to close. */ void close(); /** * Get current session state. * * @return the current session state. */ SessionState getSessionState(); /** * Get the last activity of a session. * * @return the last activity timestamp. */ long getLastActivityTimestamp(); }jsmpp-2.1.2/src/main/java/org/jsmpp/session/SessionStateListener.java000066400000000000000000000021311246113105100256700ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import org.jsmpp.extra.SessionState; /** * This listener contains an event related to the session state. * * @author uudashr * @version 1.0 * @since 2.0 * */ public interface SessionStateListener { /** * Raised when the session state changed. * * @param newState is the new state. * @param oldState is the old state. * @param source is source of changed state. */ public void onStateChange(SessionState newState, SessionState oldState, Object source); } jsmpp-2.1.2/src/main/java/org/jsmpp/session/SubmitMultiCommandTask.java000066400000000000000000000072041246113105100261440ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.PDUException; import org.jsmpp.PDUSender; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.DestinationAddress; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.ReplaceIfPresentFlag; import org.jsmpp.bean.TypeOfNumber; /** * @author uudashr * */ public class SubmitMultiCommandTask extends AbstractSendCommandTask { private String serviceType; private TypeOfNumber sourceAddrTon; private NumberingPlanIndicator sourceAddrNpi; private String sourceAddr; private DestinationAddress[] destinationAddresses; private ESMClass esmClass; private byte protocolId; private byte priorityFlag; private String scheduleDeliveryTime; private String validityPeriod; private RegisteredDelivery registeredDelivery; private ReplaceIfPresentFlag replaceIfPresentFlag; private DataCoding dataCoding; private byte smDefaultMsgId; private byte[] shortMessage; private OptionalParameter[] optionalParameters; public SubmitMultiCommandTask(PDUSender pduSender, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, DestinationAddress[] destinationAddresses, ESMClass esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, ReplaceIfPresentFlag replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter[] optionalParameters) { super(pduSender); this.serviceType = serviceType; this.sourceAddrTon = sourceAddrTon; this.sourceAddrNpi = sourceAddrNpi; this.sourceAddr = sourceAddr; this.destinationAddresses = destinationAddresses; this.esmClass = esmClass; this.protocolId = protocolId; this.priorityFlag = priorityFlag; this.scheduleDeliveryTime = scheduleDeliveryTime; this.validityPeriod = validityPeriod; this.registeredDelivery = registeredDelivery; this.replaceIfPresentFlag = replaceIfPresentFlag; this.dataCoding = dataCoding; this.smDefaultMsgId = smDefaultMsgId; this.shortMessage = shortMessage; this.optionalParameters = optionalParameters; } public void executeTask(OutputStream out, int sequenceNumber) throws PDUException, IOException { pduSender.sendSubmiMulti(out, sequenceNumber, serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destinationAddresses, esmClass, protocolId, priorityFlag, scheduleDeliveryTime, validityPeriod, registeredDelivery, replaceIfPresentFlag, dataCoding, smDefaultMsgId, shortMessage, optionalParameters); } public String getCommandName() { return "submit_multi"; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/SubmitSmCommandTask.java000066400000000000000000000075231246113105100254350ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.PDUSender; import org.jsmpp.PDUStringException; import org.jsmpp.bean.DataCoding; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.TypeOfNumber; /** * @author uudashr * */ public class SubmitSmCommandTask extends AbstractSendCommandTask { private final String serviceType; private final TypeOfNumber sourceAddrTon; private final NumberingPlanIndicator sourceAddrNpi; private final String sourceAddr; private final TypeOfNumber destAddrTon; private final NumberingPlanIndicator destAddrNpi; private final String destinationAddr; private final ESMClass esmClass; private final byte protocolId; private final byte priorityFlag; private final String scheduleDeliveryTime; private final String validityPeriod; private final RegisteredDelivery registeredDelivery; private final byte replaceIfPresentFlag; private final DataCoding dataCoding; private final byte smDefaultMsgId; private final byte[] shortMessage; private final OptionalParameter[] optionalParameters; public SubmitSmCommandTask(PDUSender pduSender, String serviceType, TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi, String sourceAddr, TypeOfNumber destAddrTon, NumberingPlanIndicator destAddrNpi, String destinationAddr, ESMClass esmClass, byte protocoId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, RegisteredDelivery registeredDelivery, byte replaceIfPresentFlag, DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) { super(pduSender); this.serviceType = serviceType; this.sourceAddrTon = sourceAddrTon; this.sourceAddrNpi = sourceAddrNpi; this.sourceAddr = sourceAddr; this.destAddrTon = destAddrTon; this.destAddrNpi = destAddrNpi; this.destinationAddr = destinationAddr; this.esmClass = esmClass; this.protocolId = protocoId; this.priorityFlag = priorityFlag; this.scheduleDeliveryTime = scheduleDeliveryTime; this.validityPeriod = validityPeriod; this.registeredDelivery = registeredDelivery; this.replaceIfPresentFlag = replaceIfPresentFlag; this.dataCoding = dataCoding; this.smDefaultMsgId = smDefaultMsgId; this.shortMessage = shortMessage; this.optionalParameters = optionalParameters; } public void executeTask(OutputStream out, int sequenceNumber) throws PDUStringException, IOException { pduSender.sendSubmitSm(out, sequenceNumber, serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi, destinationAddr, esmClass, protocolId, priorityFlag, scheduleDeliveryTime, validityPeriod, registeredDelivery, replaceIfPresentFlag, dataCoding, smDefaultMsgId, shortMessage, optionalParameters); } public String getCommandName() { return "submit_sm"; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/UnbindCommandTask.java000066400000000000000000000021201246113105100250750ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session; import java.io.IOException; import java.io.OutputStream; import org.jsmpp.PDUSender; /** * @author uudashr * */ public class UnbindCommandTask extends AbstractSendCommandTask { public UnbindCommandTask(PDUSender pduSender) { super(pduSender); } public void executeTask(OutputStream out, int sequenceNumber) throws IOException { pduSender.sendUnbind(out, sequenceNumber); } public String getCommandName() { return "unbind"; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/connection/000077500000000000000000000000001246113105100230355ustar00rootroot00000000000000jsmpp-2.1.2/src/main/java/org/jsmpp/session/connection/Connection.java000066400000000000000000000017061246113105100260030ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.connection; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Connection object. * * @author uudashr * */ public interface Connection { boolean isOpen(); InputStream getInputStream(); OutputStream getOutputStream(); void setSoTimeout(int timeout) throws IOException; void close() throws IOException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/connection/ConnectionFactory.java000066400000000000000000000014151246113105100273300ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.connection; import java.io.IOException; /** * @author uudashr * */ public interface ConnectionFactory { Connection createConnection(String host, int port) throws IOException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/connection/ServerConnection.java000066400000000000000000000016031246113105100271660ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.connection; import java.io.IOException; /** * @author uudashr * */ public interface ServerConnection { Connection accept() throws IOException; void setSoTimeout(int timeout) throws IOException; int getSoTimeout() throws IOException; void close() throws IOException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/connection/ServerConnectionFactory.java000066400000000000000000000016351246113105100305230ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.connection; import java.io.IOException; /** * @author uudashr * */ public interface ServerConnectionFactory { ServerConnection listen(int port) throws IOException; ServerConnection listen(int port, int timeout) throws IOException; ServerConnection listen(int port, int timeout, int backlog) throws IOException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/connection/socket/000077500000000000000000000000001246113105100243255ustar00rootroot00000000000000jsmpp-2.1.2/src/main/java/org/jsmpp/session/connection/socket/ServerSocketConnection.java000066400000000000000000000026751246113105100316410ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.connection.socket; import java.io.IOException; import java.net.ServerSocket; import org.jsmpp.session.connection.Connection; import org.jsmpp.session.connection.ServerConnection; /** * @author uudashr * */ public class ServerSocketConnection implements ServerConnection { private final ServerSocket serverSocket; public ServerSocketConnection(ServerSocket serverSocket) { this.serverSocket = serverSocket; } public void setSoTimeout(int timeout) throws IOException { serverSocket.setSoTimeout(timeout); } public int getSoTimeout() throws IOException { return serverSocket.getSoTimeout(); } public Connection accept() throws IOException { return new SocketConnection(serverSocket.accept()); } public void close() throws IOException { serverSocket.close(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/connection/socket/ServerSocketConnectionFactory.java000066400000000000000000000027461246113105100331700ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.connection.socket; import java.io.IOException; import java.net.ServerSocket; import org.jsmpp.session.connection.ServerConnection; import org.jsmpp.session.connection.ServerConnectionFactory; /** * @author uudashr * */ public class ServerSocketConnectionFactory implements ServerConnectionFactory { public ServerConnection listen(int port) throws IOException { return new ServerSocketConnection(new ServerSocket(port)); } public ServerConnection listen(int port, int timeout) throws IOException { ServerSocket ss = new ServerSocket(port); ss.setSoTimeout(timeout); return new ServerSocketConnection(ss); } public ServerConnection listen(int port, int timeout, int backlog) throws IOException { ServerSocket ss = new ServerSocket(port, backlog); ss.setSoTimeout(timeout); return new ServerSocketConnection(ss); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/connection/socket/SocketConnection.java000066400000000000000000000032711246113105100304430ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.connection.socket; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import org.jsmpp.session.connection.Connection; import org.jsmpp.util.StrictBufferedInputStream; /** * @author uudashr * */ public class SocketConnection implements Connection { private final Socket socket; private final InputStream in; private final OutputStream out; public SocketConnection(Socket socket) throws IOException { this.socket = socket; this.in = new StrictBufferedInputStream(socket.getInputStream(), 65536);// 64 KB buffer this.out = socket.getOutputStream(); } public void setSoTimeout(int timeout) throws IOException { socket.setSoTimeout(timeout); } public void close() { try { socket.close(); } catch (IOException e) { } } public boolean isOpen() { return !socket.isClosed(); } public InputStream getInputStream() { return in; } public OutputStream getOutputStream() { return out; } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/connection/socket/SocketConnectionFactory.java000066400000000000000000000024011246113105100317650ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.connection.socket; import java.io.IOException; import java.net.Socket; import org.jsmpp.session.connection.Connection; import org.jsmpp.session.connection.ConnectionFactory; /** * @author uudashr * */ public class SocketConnectionFactory implements ConnectionFactory { private static final SocketConnectionFactory connFactory = new SocketConnectionFactory(); public static SocketConnectionFactory getInstance() { return connFactory; } private SocketConnectionFactory() { } public Connection createConnection(String host, int port) throws IOException { return new SocketConnection(new Socket(host, port)); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/000077500000000000000000000000001246113105100220165ustar00rootroot00000000000000jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/AbstractGenericSMPPSessionBound.java000066400000000000000000000134551246113105100307650ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.GenericNackResponseException; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.Command; import org.jsmpp.bean.DataSm; import org.jsmpp.bean.DataSmResp; import org.jsmpp.bean.EnquireLinkResp; import org.jsmpp.bean.UnbindResp; import org.jsmpp.extra.PendingResponse; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.session.BaseResponseHandler; import org.jsmpp.session.DataSmResult; import org.jsmpp.util.DefaultDecomposer; import org.jsmpp.util.IntUtil; import org.jsmpp.util.PDUDecomposer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author uudashr * */ abstract class AbstractGenericSMPPSessionBound implements GenericSMPPSessionState { protected static final PDUDecomposer pduDecomposer = new DefaultDecomposer(); private static final Logger logger = LoggerFactory.getLogger(AbstractGenericSMPPSessionBound.class); public void processEnquireLink(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { responseHandler.sendEnquireLinkResp(pduHeader.getSequenceNumber()); } public void processEnquireLinkResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(pduHeader.getSequenceNumber()); if (pendingResp != null) { EnquireLinkResp resp = pduDecomposer.enquireLinkResp(pdu); pendingResp.done(resp); } else { logger.error("No request found for " + pduHeader); } } public void processUnbind(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { logger.info("Receving unbind request"); try { responseHandler.sendUnbindResp(pduHeader.getSequenceNumber()); } finally { responseHandler.notifyUnbonded(); } } public void processUnbindResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(pduHeader.getSequenceNumber()); if (pendingResp != null) { UnbindResp resp = pduDecomposer.unbindResp(pdu); pendingResp.done(resp); } else { logger.error("No request found for " + pduHeader); } } public void processUnknownCid(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { responseHandler.sendGenerickNack(SMPPConstant.STAT_ESME_RINVCMDID, pduHeader.getSequenceNumber()); } public void processGenericNack(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(pduHeader.getSequenceNumber()); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new GenericNackResponseException( "Receive generic_nack with command_status " + pduHeader.getCommandStatusAsHex(), pduHeader.getCommandStatus())); logger.error("Receive generick_nack. " + "command_status=" + pduHeader.getCommandStatusAsHex() + ", sequence_number=" + IntUtil.toHexString(pduHeader.getSequenceNumber())); } } public void processDataSm(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { try { DataSm dataSm = pduDecomposer.dataSm(pdu); DataSmResult dataSmResult = responseHandler.processDataSm(dataSm); logger.debug("Sending response with message_id " + dataSmResult.getMessageId() + " for request with sequence_number " + pduHeader.getSequenceNumber()); responseHandler.sendDataSmResp(dataSmResult, pduHeader.getSequenceNumber()); } catch (PDUStringException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e.getErrorCode(), pduHeader.getSequenceNumber()); } catch (ProcessRequestException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e.getErrorCode(), pduHeader.getSequenceNumber()); } } public void processDataSmResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(pduHeader.getSequenceNumber()); if (pendingResp != null) { try { DataSmResp resp = pduDecomposer.dataSmResp(pdu); pendingResp.done(resp); } catch (PDUStringException e) { logger.error("Failed decomposing data_sm_resp", e); responseHandler.sendGenerickNack(e.getErrorCode(), pduHeader .getSequenceNumber()); } } else { logger.warn("No request with sequence number " + pduHeader.getSequenceNumber() + " found"); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/GenericSMPPSessionState.java000066400000000000000000000101641246113105100273040ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.bean.Command; import org.jsmpp.extra.SessionState; import org.jsmpp.session.BaseResponseHandler; /** * @author uudashr * */ interface GenericSMPPSessionState { /** * Get the associated session state value. * * @return the {@link SessionState} associated by the interface implementation. */ SessionState getSessionState(); /** * Process the generick_nack command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processGenericNack(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException; /** * Process the enquire_link command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processEnquireLink(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException; /** * Process the enquire_link_resp command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processEnquireLinkResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException; /** * Process the unbind command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processUnbind(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException; /** * Process the unbind_resp command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processUnbindResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException; /** * Process the unknown command id. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processUnknownCid(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException; /** * Process the data short message request command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processDataSm(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException; /** * Process the data short message response command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processDataSmResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPServerSessionBound.java000066400000000000000000000022471246113105100271700ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.Command; import org.jsmpp.session.ServerResponseHandler; /** * @author uudashr * */ abstract class SMPPServerSessionBound extends AbstractGenericSMPPSessionBound implements SMPPServerSessionState { public void processBind(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RALYBND, pduHeader.getSequenceNumber()); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPServerSessionBoundRX.java000066400000000000000000000070701246113105100274410ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.Command; import org.jsmpp.bean.DeliverSmResp; import org.jsmpp.extra.PendingResponse; import org.jsmpp.extra.SessionState; import org.jsmpp.session.ServerResponseHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author uudashr * */ class SMPPServerSessionBoundRX extends SMPPServerSessionBound implements SMPPServerSessionState { private static final Logger logger = LoggerFactory.getLogger(SMPPServerSessionBoundRX.class); public SessionState getSessionState() { return SessionState.BOUND_RX; } public void processDeliverSmResp(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { processDeliverSmResp0(pduHeader, pdu, responseHandler); } public void processQuerySm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processSubmitSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processSubmitMulti(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processCancelSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processReplaceSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } static final void processDeliverSmResp0(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler.removeSentItem(pduHeader.getSequenceNumber()); if (pendingResp != null) { DeliverSmResp resp = pduDecomposer.deliverSmResp(pdu); pendingResp.done(resp); } else { logger.warn("No request with sequence number " + pduHeader.getSequenceNumber() + " found"); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPServerSessionBoundTX.java000066400000000000000000000140421246113105100274400ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.InvalidNumberOfDestinationsException; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.CancelSm; import org.jsmpp.bean.Command; import org.jsmpp.bean.QuerySm; import org.jsmpp.bean.ReplaceSm; import org.jsmpp.bean.SubmitMulti; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.SubmitSm; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.extra.SessionState; import org.jsmpp.session.QuerySmResult; import org.jsmpp.session.ServerResponseHandler; import org.jsmpp.util.MessageId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author uudashr * */ class SMPPServerSessionBoundTX extends SMPPServerSessionBound implements SMPPServerSessionState { private static final Logger logger = LoggerFactory.getLogger(SMPPServerSessionBoundTX.class); public SessionState getSessionState() { return SessionState.BOUND_TX; } public void processDeliverSmResp(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processSubmitSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { try { SubmitSm submitSm = pduDecomposer.submitSm(pdu); MessageId messageId = responseHandler.processSubmitSm(submitSm); logger.debug("Sending response with message_id " + messageId + " for request with sequence_number " + pduHeader.getSequenceNumber()); responseHandler.sendSubmitSmResponse(messageId, pduHeader.getSequenceNumber()); } catch (PDUStringException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e.getErrorCode(), pduHeader.getSequenceNumber()); } catch (ProcessRequestException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e.getErrorCode(), pduHeader.getSequenceNumber()); } } public void processSubmitMulti(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { try { SubmitMulti submitMulti = pduDecomposer.submitMulti(pdu); SubmitMultiResult result = responseHandler.processSubmitMulti(submitMulti); logger.debug("Sending response with message_id " + result.getMessageId() + " for request with sequence_number " + pduHeader.getSequenceNumber()); responseHandler.sendSubmitMultiResponse(result, pduHeader.getSequenceNumber()); } catch (PDUStringException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e.getErrorCode(), pduHeader.getSequenceNumber()); } catch (InvalidNumberOfDestinationsException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVNUMDESTS, pduHeader.getSequenceNumber()); } catch (ProcessRequestException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e.getErrorCode(), pduHeader.getSequenceNumber()); } } public void processQuerySm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { try { QuerySm querySm = pduDecomposer.querySm(pdu); QuerySmResult result = responseHandler.processQuerySm(querySm); responseHandler.sendQuerySmResp(querySm.getMessageId(), result.getFinalDate(), result.getMessageState(), result.getErrorCode(), pduHeader.getSequenceNumber()); } catch (PDUStringException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e.getErrorCode(), pduHeader.getSequenceNumber()); } catch (ProcessRequestException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e.getErrorCode(), pduHeader.getSequenceNumber()); } } public void processCancelSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { try { CancelSm cancelSm = pduDecomposer.cancelSm(pdu); responseHandler.processCancelSm(cancelSm); responseHandler.sendCancelSmResp(pduHeader.getSequenceNumber()); } catch (PDUStringException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e.getErrorCode(), pduHeader.getSequenceNumber()); } catch (ProcessRequestException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e.getErrorCode(), pduHeader.getSequenceNumber()); } } public void processReplaceSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { try { ReplaceSm replaceSm = pduDecomposer.replaceSm(pdu); responseHandler.processReplaceSm(replaceSm); responseHandler.sendReplaceSmResp(pduHeader.getSequenceNumber()); } catch (PDUStringException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e.getErrorCode(), pduHeader.getSequenceNumber()); } catch (ProcessRequestException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e.getErrorCode(), pduHeader.getSequenceNumber()); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPServerSessionClosed.java000066400000000000000000000102451246113105100273270ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.bean.Command; import org.jsmpp.extra.SessionState; import org.jsmpp.session.BaseResponseHandler; import org.jsmpp.session.ServerResponseHandler; /** * @author uudashr * */ class SMPPServerSessionClosed implements SMPPServerSessionState { public SessionState getSessionState() { return SessionState.CLOSED; } public void processBind(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processDeliverSmResp(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processQuerySm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processSubmitSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processSubmitMulti(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processEnquireLink(Command pduHeader, byte[] pdu, BaseResponseHandler sessionHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processEnquireLinkResp(Command pduHeader, byte[] pdu, BaseResponseHandler sessionHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processGenericNack(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processUnbind(Command pduHeader, byte[] pdu, BaseResponseHandler sessionHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processUnbindResp(Command pduHeader, byte[] pdu, BaseResponseHandler sessionHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processUnknownCid(Command pduHeader, byte[] pdu, BaseResponseHandler sessionHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processDataSm(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processDataSmResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processCancelSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processReplaceSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPServerSessionOpen.java000066400000000000000000000117361246113105100270250ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.Bind; import org.jsmpp.bean.Command; import org.jsmpp.extra.SessionState; import org.jsmpp.session.BaseResponseHandler; import org.jsmpp.session.ServerResponseHandler; import org.jsmpp.util.DefaultDecomposer; import org.jsmpp.util.PDUDecomposer; /** * @author uudashr * */ class SMPPServerSessionOpen implements SMPPServerSessionState { private static final PDUDecomposer pduDecomposer = new DefaultDecomposer(); public SessionState getSessionState() { return SessionState.OPEN; } public void processBind(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { try { Bind bind = pduDecomposer.bind(pdu); responseHandler.processBind(bind); //responseHandler.sendBindResp(BindType.valueOf(pduHeader.getCommandId()), pduHeader.getSequenceNumber()); } catch (PDUStringException e) { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e.getErrorCode(), pduHeader.getSequenceNumber()); } catch (IllegalArgumentException e) { // TODO uudashr: might not need anymore responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVCMDID, pduHeader.getSequenceNumber()); } } public void processDeliverSmResp(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for open session state"); } public void processQuerySm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for open session state"); } public void processSubmitSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for open session state"); } public void processSubmitMulti(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for open session state"); } public void processEnquireLink(Command pduHeader, byte[] pdu, BaseResponseHandler sessionHandler) throws IOException { throw new IOException("Invalid process for open session state"); } public void processEnquireLinkResp(Command pduHeader, byte[] pdu, BaseResponseHandler sessionHandler) throws IOException { throw new IOException("Invalid process for open session state"); } public void processGenericNack(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for open session state"); } public void processUnbind(Command pduHeader, byte[] pdu, BaseResponseHandler sessionHandler) throws IOException { throw new IOException("Invalid process for open session state"); } public void processUnbindResp(Command pduHeader, byte[] pdu, BaseResponseHandler sessionHandler) throws IOException { throw new IOException("Invalid process for open session state"); } public void processUnknownCid(Command pduHeader, byte[] pdu, BaseResponseHandler sessionHandler) throws IOException { throw new IOException("Invalid process for open session state"); } public void processDataSm(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for open session state"); } public void processDataSmResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for open session state"); } public void processCancelSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for open session state"); } public void processReplaceSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for open session state"); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPServerSessionState.java000066400000000000000000000057671246113105100272130ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.bean.Command; import org.jsmpp.session.ServerResponseHandler; /** * @author uudashr * */ public interface SMPPServerSessionState extends GenericSMPPSessionState { public static final SMPPServerSessionState OPEN = new SMPPServerSessionOpen(); public static final SMPPServerSessionState BOUND_RX = new SMPPServerSessionBoundRX(); public static final SMPPServerSessionState BOUND_TX = new SMPPServerSessionBoundTX(); public static final SMPPServerSessionState BOUND_TRX = new SMPPServerSessionTRX(); public static final SMPPServerSessionState UNBOUND = new SMPPServerSessionUnbound(); public static final SMPPServerSessionState CLOSED = new SMPPServerSessionClosed(); /** * Process the bind request command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the response handler. * @throws IOException if there is an IO error occur. */ void processBind(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException; /** * Process the submit short message request command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the response handler. * @throws IOException */ void processSubmitSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException; void processSubmitMulti(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException; void processQuerySm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException; void processDeliverSmResp(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException; /** * Process the cancel short message request command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processCancelSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException; void processReplaceSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException; } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPServerSessionTRX.java000066400000000000000000000022651246113105100265760ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.bean.Command; import org.jsmpp.extra.SessionState; import org.jsmpp.session.ServerResponseHandler; /** * @author uudashr * */ class SMPPServerSessionTRX extends SMPPServerSessionBoundTX { @Override public SessionState getSessionState() { return SessionState.BOUND_TRX; } @Override public void processDeliverSmResp(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { SMPPServerSessionBoundRX.processDeliverSmResp0(pduHeader, pdu, responseHandler); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPServerSessionUnbound.java000066400000000000000000000103461246113105100275320ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.bean.Command; import org.jsmpp.extra.SessionState; import org.jsmpp.session.BaseResponseHandler; import org.jsmpp.session.ServerResponseHandler; /** * @author uudashr * */ public class SMPPServerSessionUnbound implements SMPPServerSessionState { public SessionState getSessionState() { return SessionState.UNBOUND; } public void processBind(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processDeliverSmResp(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processQuerySm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processSubmitSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processSubmitMulti(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processEnquireLink(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processEnquireLinkResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processGenericNack(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processUnbind(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processUnbindResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processUnknownCid(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processDataSm(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processDataSmResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processCancelSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processReplaceSm(Command pduHeader, byte[] pdu, ServerResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPSessionBound.java000066400000000000000000000023771246113105100260050ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.Command; import org.jsmpp.session.ResponseHandler; /** * This class is general bound state implementation of {@link SMPPSessionState}. * * @author uudashr * @version 1.0 * @since 2.0 * */ abstract class SMPPSessionBound extends AbstractGenericSMPPSessionBound implements SMPPSessionState { public void processBindResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RALYBND, pduHeader.getSequenceNumber()); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPSessionBoundRX.java000066400000000000000000000115621246113105100262530ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.AlertNotification; import org.jsmpp.bean.Command; import org.jsmpp.bean.DeliverSm; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.extra.SessionState; import org.jsmpp.session.ResponseHandler; import org.jsmpp.util.DefaultDecomposer; import org.jsmpp.util.PDUDecomposer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is bound_tx state implementation of {@link SMPPSessionState}. * Response to receiver related transaction. * * @author uudashr * @version 1.0 * @since 2.0 * */ class SMPPSessionBoundRX extends SMPPSessionBound implements SMPPSessionState { private static final Logger logger = LoggerFactory.getLogger(SMPPSessionBoundRX.class); private static final PDUDecomposer pduDecomposer = new DefaultDecomposer(); public SessionState getSessionState() { return SessionState.BOUND_RX; } public void processDeliverSm(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { processDeliverSm0(pduHeader, pdu, responseHandler); } public void processSubmitSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processSubmitMultiResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processQuerySmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processCancelSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processReplaceSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processAlertNotification(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) { processAlertNotification0(pduHeader, pdu, responseHandler); } static void processAlertNotification0(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) { try { AlertNotification alertNotification = pduDecomposer.alertNotification(pdu); responseHandler.processAlertNotification(alertNotification); } catch (PDUStringException e) { logger.error("Failed decomposing alert_notification", e); // there is no response for alert notification } } static void processDeliverSm0(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { try { DeliverSm deliverSm = pduDecomposer.deliverSm(pdu); responseHandler.processDeliverSm(deliverSm); responseHandler.sendDeliverSmResp(pduHeader.getSequenceNumber()); } catch (PDUStringException e) { logger.error("Failed decomposing deliver_sm", e); responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e .getErrorCode(), pduHeader.getSequenceNumber()); } catch (ProcessRequestException e) { logger.error("Failed processing deliver_sm", e); responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e .getErrorCode(), pduHeader.getSequenceNumber()); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPSessionBoundTRX.java000066400000000000000000000025361246113105100264000ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.bean.Command; import org.jsmpp.extra.SessionState; import org.jsmpp.session.ResponseHandler; /** * This class is bound_trx state implementation of {@link SMPPSessionState}. * Response both to transmit and receive related transaction. * * @author uudashr * @version 1.0 * @since 2.0 * */ class SMPPSessionBoundTRX extends SMPPSessionBoundTX implements SMPPSessionState { @Override public SessionState getSessionState() { return SessionState.BOUND_TRX; } @Override public void processDeliverSm(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { SMPPSessionBoundRX.processDeliverSm0(pduHeader, pdu, responseHandler); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPSessionBoundTX.java000066400000000000000000000134731246113105100262600ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.CancelSmResp; import org.jsmpp.bean.Command; import org.jsmpp.bean.QuerySmResp; import org.jsmpp.bean.ReplaceSmResp; import org.jsmpp.bean.SubmitMultiResp; import org.jsmpp.bean.SubmitSmResp; import org.jsmpp.extra.PendingResponse; import org.jsmpp.extra.SessionState; import org.jsmpp.session.ResponseHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is unbound state implementation of {@link SMPPSessionState}. This * class give specific response to a transmit related transaction, otherwise * it always give negative response. * * @author uudashr * @version 1.0 * @since 2.0 * */ class SMPPSessionBoundTX extends SMPPSessionBound implements SMPPSessionState { private static final Logger logger = LoggerFactory.getLogger(SMPPSessionBoundTX.class); public SessionState getSessionState() { return SessionState.BOUND_TX; } public void processSubmitSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(pduHeader.getSequenceNumber()); if (pendingResp != null) { try { SubmitSmResp resp = pduDecomposer.submitSmResp(pdu); pendingResp.done(resp); } catch (PDUStringException e) { logger.error("Failed decomposing submit_sm_resp", e); responseHandler.sendGenerickNack(e.getErrorCode(), pduHeader .getSequenceNumber()); } } else { logger.warn("No request with sequence number " + pduHeader.getSequenceNumber() + " found"); } } public void processSubmitMultiResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(pduHeader.getSequenceNumber()); if (pendingResp != null) { try { SubmitMultiResp resp = pduDecomposer.submitMultiResp(pdu); pendingResp.done(resp); } catch (PDUStringException e) { logger.error("Failed decomposing submit_multi_resp", e); responseHandler.sendGenerickNack(e.getErrorCode(), pduHeader .getSequenceNumber()); } } else { logger.warn("No request with sequence number " + pduHeader.getSequenceNumber() + " found"); } } public void processQuerySmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(pduHeader.getSequenceNumber()); if (pendingResp != null) { try { QuerySmResp resp = pduDecomposer.querySmResp(pdu); pendingResp.done(resp); } catch (PDUStringException e) { logger.error("Failed decomposing submit_sm_resp", e); responseHandler.sendGenerickNack(e.getErrorCode(), pduHeader .getSequenceNumber()); } } else { logger.error("No request find for sequence number " + pduHeader.getSequenceNumber()); responseHandler.sendGenerickNack( SMPPConstant.STAT_ESME_RINVDFTMSGID, pduHeader .getSequenceNumber()); } } public void processCancelSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(pduHeader.getSequenceNumber()); if (pendingResp != null) { CancelSmResp resp = pduDecomposer.cancelSmResp(pdu); pendingResp.done(resp); } else { logger.error("No request find for sequence number " + pduHeader.getSequenceNumber()); } } public void processReplaceSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(pduHeader.getSequenceNumber()); if (pendingResp != null) { ReplaceSmResp resp = pduDecomposer.replaceSmResp(pdu); pendingResp.done(resp); } else { logger.error("No request find for sequence number " + pduHeader.getSequenceNumber()); } } public void processDeliverSm(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processAlertNotification(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) { logger.error("Receiving alert_notification while on invalid bound state (transmitter)"); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPSessionClosed.java000066400000000000000000000113371246113105100261430ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.bean.Command; import org.jsmpp.extra.SessionState; import org.jsmpp.session.BaseResponseHandler; import org.jsmpp.session.ResponseHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is closed state implementation of {@link SMPPSessionState}. This * session state on SMPP specification context, implemented on since version 5.0, * but we can also use this. * * @author uudashr * @version 1.0 * @since 2.0 * */ class SMPPSessionClosed implements SMPPSessionState { private static final Logger logger = LoggerFactory.getLogger(SMPPSessionClosed.class); public SessionState getSessionState() { return SessionState.CLOSED; } public void processBindResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processDeliverSm(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processEnquireLink(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processEnquireLinkResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processGenericNack(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processQuerySmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processSubmitSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processSubmitMultiResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processUnbind(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processUnbindResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processUnknownCid(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processDataSm(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processDataSmResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processCancelSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processReplaceSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for closed session state"); } public void processAlertNotification(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) { logger.error("SYSTEM ERROR. Receiving alert_notification while on invalid closed state"); } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPSessionOpen.java000066400000000000000000000224021246113105100256260ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.BindResp; import org.jsmpp.bean.Command; import org.jsmpp.extra.PendingResponse; import org.jsmpp.extra.SessionState; import org.jsmpp.session.BaseResponseHandler; import org.jsmpp.session.ResponseHandler; import org.jsmpp.util.DefaultDecomposer; import org.jsmpp.util.IntUtil; import org.jsmpp.util.PDUDecomposer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is open state implementation of {@link SMPPSessionState}. When * the session state is open, we only give positive response to bind related intention. * * @author uudashr * @version 1.0 * @since 2.0 * */ class SMPPSessionOpen implements SMPPSessionState { private static final Logger logger = LoggerFactory.getLogger(SMPPSessionOpen.class); private static final PDUDecomposer pduDecomposer = new DefaultDecomposer(); public SessionState getSessionState() { return SessionState.OPEN; } public void processBindResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(pduHeader.getSequenceNumber()); if (pendingResp != null) { try { logger.debug("Bind Response header (" + pduHeader.getCommandLength() + ", " + pduHeader.getCommandIdAsHex() + ", " + IntUtil.toHexString(pduHeader.getCommandStatus()) + ", " + pduHeader.getSequenceNumber() + ")"); BindResp resp = pduDecomposer.bindResp(pdu); pendingResp.done(resp); } catch (PDUStringException e) { String message = "Failed decomposing submit_sm_resp"; logger.error(message, e); responseHandler.sendGenerickNack(e.getErrorCode(), pduHeader .getSequenceNumber()); pendingResp .doneWithInvalidResponse(new InvalidResponseException( message, e)); } } else { logger.error("No request with sequence number " + pduHeader.getSequenceNumber() + " found"); responseHandler.sendGenerickNack( SMPPConstant.STAT_ESME_RINVDFTMSGID, pduHeader .getSequenceNumber()); } } public void processDeliverSm(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected deliver_sm")); } } public void processEnquireLink(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected enquire_link")); } } public void processEnquireLinkResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected enquire_link_resp")); } } public void processGenericNack(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected generic_nack")); } } public void processSubmitSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected submit_sm_resp")); } } public void processSubmitMultiResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected submit_multi_resp")); } } public void processUnbind(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected unbind")); } } public void processUnbindResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected unbind_resp")); } } public void processUnknownCid(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unknown command_id")); } } public void processQuerySmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected query_sm")); } } public void processDataSm(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected data_sm")); } } public void processDataSmResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected data_sm_resp")); } } public void processCancelSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected cancel_sm_resp")); } } public void processReplaceSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { PendingResponse pendingResp = responseHandler.removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected replace_sm_resp")); } } public void processAlertNotification(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) { PendingResponse pendingResp = responseHandler .removeSentItem(1); if (pendingResp != null) { pendingResp.doneWithInvalidResponse(new InvalidResponseException( "Receive unexpected alert_notification")); } } } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPSessionState.java000066400000000000000000000074361246113105100260170ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.bean.Command; import org.jsmpp.session.ResponseHandler; /** * This class is provide interface to response to every incoming SMPP Commands. * How the the response behavior is depends to it's states, or the * implementation of this class. * * @author uudashr * @version 1.0 * @since 2.0 */ public interface SMPPSessionState extends GenericSMPPSessionState { public static final SMPPSessionState OPEN = new SMPPSessionOpen(); public static final SMPPSessionState BOUND_RX = new SMPPSessionBoundRX(); public static final SMPPSessionState BOUND_TX = new SMPPSessionBoundTX(); public static final SMPPSessionState BOUND_TRX = new SMPPSessionBoundTRX(); public static final SMPPSessionState UNBOUND = new SMPPSessionUnbound(); public static final SMPPSessionState CLOSED = new SMPPSessionClosed(); /** * Process the bind response command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processBindResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; /** * Process the submit short message response command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the response handler. * @throws IOException if there is an I/O error found. */ void processSubmitSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; /** * Process a submit multiple message response. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the response handler. * @throws IOException if there is an I/O error found. */ void processSubmitMultiResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; /** * Process the query short message response command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processQuerySmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; /** * Process the deliver short message request command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processDeliverSm(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; void processCancelSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; void processReplaceSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; void processAlertNotification(Command pduHeader, byte[] pdu, ResponseHandler responseHandler); } jsmpp-2.1.2/src/main/java/org/jsmpp/session/state/SMPPSessionUnbound.java000066400000000000000000000113641246113105100263440ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.bean.Command; import org.jsmpp.extra.SessionState; import org.jsmpp.session.BaseResponseHandler; import org.jsmpp.session.ResponseHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is unbound state implementation of {@link SMPPSessionState}. All * this method is throw {@link IOException} since when the state is unbound we * should not give any positive response. * * @author uudashr * @version 1.0 * @since 2.0 * */ class SMPPSessionUnbound implements SMPPSessionState { private static final Logger logger = LoggerFactory.getLogger(SMPPSessionUnbound.class); public SessionState getSessionState() { return SessionState.UNBOUND; } public void processBindResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processDeliverSm(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processEnquireLink(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processEnquireLinkResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processGenericNack(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processSubmitSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processSubmitMultiResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processUnbind(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processUnbindResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processUnknownCid(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processQuerySmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processDataSm(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processDataSmResp(Command pduHeader, byte[] pdu, BaseResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processCancelSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processReplaceSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { throw new IOException("Invalid process for unbound session state"); } public void processAlertNotification(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) { logger.error("SYSTEM ERROR. Receiving alert_notification while on unbound state"); } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/000077500000000000000000000000001246113105100201705ustar00rootroot00000000000000jsmpp-2.1.2/src/main/java/org/jsmpp/util/AbsoluteTimeFormatter.java000066400000000000000000000053341246113105100253210ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import java.text.MessageFormat; import java.util.Calendar; import java.util.Date; /** * Absolute time formatter is {@link TimeFormatter} implementation referred to * SMPP Protocol Specification v3.4 point 7.1.1. * * @author uudashr * */ public class AbsoluteTimeFormatter implements TimeFormatter { /** * Time/Date ASCII format for Absolute Time Format is: * * YYMMDDhhmmsstnnp (refer for SMPP Protocol Specification v3.4) */ private static final String DATE_FORMAT = "{0,number,00}{1,number,00}{2,number,00}{3,number,00}{4,number,00}{5,number,00}{6,number,0}{7,number,00}{8}"; public String format(Calendar calendar) { if (calendar == null) { return null; } int year = calendar.get(Calendar.YEAR) - 2000; int month = calendar.get(Calendar.MONTH) + 1; int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); int tenthsOfSecond = calendar.get(Calendar.MILLISECOND) / 100; int rawOffset = calendar.getTimeZone().getRawOffset(); // Get the sign char sign; if (rawOffset > 0) { sign = '+'; } else { sign = '-'; } // Time difference in quarter hours int timeDiff = (int)(Math.abs(rawOffset) / (15 * 60 * 1000)); return format(year, month, day, hour, minute, second, tenthsOfSecond, timeDiff, sign); } public String format(Date date) { if (date == null) { return null; } Calendar cal = Calendar.getInstance(); cal.setTime(date); return format(cal); } public static final String format(Integer year, Integer month, Integer day, Integer hour, Integer minute, Integer second, int tenthsOfSecond, int timeDiff, Character sign) { Object[] args = new Object[] {year, month, day, hour, minute, second, tenthsOfSecond, timeDiff, sign}; return MessageFormat.format(DATE_FORMAT, args); } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/CapacityPolicy.java000066400000000000000000000021651246113105100237540ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * It's capacity policy that ensure the new capacity is save for accommodate the * new item with new capacity. * * @author uudashr * */ public interface CapacityPolicy { /** * Ensuring the currentCapacity is save to accommodate new items that * totally defined as requiredCapacity. * * @param requiredCapacity is the required capacity. * @param currentCapacity is the current capacity. * @return the new save capacity. */ int ensureCapacity(int requiredCapacity, int currentCapacity); } jsmpp-2.1.2/src/main/java/org/jsmpp/util/DefaultComposer.java000066400000000000000000000541041246113105100241330ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import org.jsmpp.InvalidNumberOfDestinationsException; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.Address; import org.jsmpp.bean.DestinationAddress; import org.jsmpp.bean.DistributionList; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.UnsuccessDelivery; import org.jsmpp.bean.OptionalParameter.Tag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Default implementation of {@link PDUComposer}. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class DefaultComposer implements PDUComposer { private static final Logger logger = LoggerFactory.getLogger(DefaultComposer.class); public DefaultComposer() { } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#composeHeader(int, int, int) */ public byte[] composeHeader(int commandId, int commandStatus, int sequenceNumber) { PDUByteBuffer buf = new PDUByteBuffer(commandId, commandStatus, sequenceNumber); return buf.toBytes(); } // GENERAL BIND OPERATION /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#bind(int, int, java.lang.String, * java.lang.String, java.lang.String, byte, byte, byte, * java.lang.String) */ public byte[] bind(int commandId, int sequenceNumber, String systemId, String password, String systemType, byte interfaceVersion, byte addrTon, byte addrNpi, String addressRange) throws PDUStringException { StringValidator.validateString(systemId, StringParameter.SYSTEM_ID); StringValidator.validateString(password, StringParameter.PASSWORD); StringValidator.validateString(systemType, StringParameter.SYSTEM_TYPE); StringValidator.validateString(addressRange, StringParameter.ADDRESS_RANGE); PDUByteBuffer buf = new PDUByteBuffer(commandId, 0, sequenceNumber); buf.append(systemId); buf.append(password); buf.append(systemType); buf.append(interfaceVersion); buf.append(addrTon); buf.append(addrNpi); buf.append(addressRange); return buf.toBytes(); } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#bindResp(int, int, java.lang.String, * org.jsmpp.bean.OptionalParameter[]) */ public byte[] bindResp(int commandId, int sequenceNumber, String systemId, OptionalParameter... optionalParameters) throws PDUStringException { StringValidator.validateString(systemId, StringParameter.SYSTEM_ID); PDUByteBuffer buf = new PDUByteBuffer(commandId, 0, sequenceNumber); buf.append(systemId); buf.appendAll(optionalParameters); return buf.toBytes(); } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#bindResp(int, int, java.lang.String, * byte) */ public byte[] bindResp(int commandId, int sequenceNumber, String systemId, byte scInterfaceVersion) throws PDUStringException { StringValidator.validateString(systemId, StringParameter.SYSTEM_ID); PDUByteBuffer buf = new PDUByteBuffer(commandId, 0, sequenceNumber); buf.append(systemId); OptionalParameter optParam = new OptionalParameter.Byte( Tag.SC_INTERFACE_VERSION, scInterfaceVersion); buf.append(optParam.serialize()); return buf.toBytes(); } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#unbind(int) */ public byte[] unbind(int sequenceNumber) { PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_UNBIND, 0, sequenceNumber); return buf.toBytes(); } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#unbindResp(int, int) */ public byte[] unbindResp(int commandStatus, int sequenceNumber) { return composeHeader(SMPPConstant.CID_UNBIND_RESP, commandStatus, sequenceNumber); } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#outbind(int, java.lang.String, * java.lang.String) */ public byte[] outbind(int sequenceNumber, String systemId, String password) throws PDUStringException { StringValidator.validateString(systemId, StringParameter.SYSTEM_ID); StringValidator.validateString(password, StringParameter.PASSWORD); PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_OUTBIND, 0, sequenceNumber); buf.append(systemId); buf.append(password); return buf.toBytes(); } // ENQUIRE_LINK OPERATION /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#enquireLink(int) */ public byte[] enquireLink(int sequenceNumber) { return composeHeader(SMPPConstant.CID_ENQUIRE_LINK, 0, sequenceNumber); } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#enquireLinkResp(int) */ public byte[] enquireLinkResp(int sequenceNumber) { return composeHeader(SMPPConstant.CID_ENQUIRE_LINK_RESP, 0, sequenceNumber); } // GENEICK_NACK OPERATION /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#genericNack(int, int) */ public byte[] genericNack(int commandStatus, int sequenceNumber) { return composeHeader(SMPPConstant.CID_GENERIC_NACK, commandStatus, sequenceNumber); } // SUBMIT_SM OPERATION /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#submitSm(int, java.lang.String, byte, * byte, java.lang.String, byte, byte, java.lang.String, byte, byte, * byte, java.lang.String, java.lang.String, byte, byte, byte, byte, * byte[], org.jsmpp.bean.OptionalParameter[]) */ public byte[] submitSm(int sequenceNumber, String serviceType, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte destAddrTon, byte destAddrNpi, String destinationAddr, byte esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, byte registeredDelivery, byte replaceIfPresentFlag, byte dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException { StringValidator.validateString(serviceType, StringParameter.SERVICE_TYPE); StringValidator.validateString(sourceAddr, StringParameter.SOURCE_ADDR); StringValidator.validateString(destinationAddr, StringParameter.DESTINATION_ADDR); StringValidator.validateString(scheduleDeliveryTime, StringParameter.SCHEDULE_DELIVERY_TIME); StringValidator.validateString(validityPeriod, StringParameter.VALIDITY_PERIOD); StringValidator.validateString(shortMessage, StringParameter.SHORT_MESSAGE); PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_SUBMIT_SM, 0, sequenceNumber); buf.append(serviceType); buf.append(sourceAddrTon); buf.append(sourceAddrNpi); buf.append(sourceAddr); buf.append(destAddrTon); buf.append(destAddrNpi); buf.append(destinationAddr); buf.append(esmClass); buf.append(protocolId); buf.append(priorityFlag); buf.append(scheduleDeliveryTime); buf.append(validityPeriod); buf.append(registeredDelivery); buf.append(replaceIfPresentFlag); buf.append(dataCoding); buf.append(smDefaultMsgId); buf.append((byte)shortMessage.length); buf.append(shortMessage); buf.appendAll(optionalParameters); return buf.toBytes(); } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#submitSmResp(int, java.lang.String) */ public byte[] submitSmResp(int sequenceNumber, String messageId) throws PDUStringException { StringValidator.validateString(messageId, StringParameter.MESSAGE_ID); PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_SUBMIT_SM_RESP, 0, sequenceNumber); buf.append(messageId); return buf.toBytes(); } // QUERY_SM OPERATION /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#querySm(int, java.lang.String, byte, * byte, java.lang.String) */ public byte[] querySm(int sequenceNumber, String messageId, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr) throws PDUStringException { StringValidator.validateString(messageId, StringParameter.MESSAGE_ID); StringValidator.validateString(sourceAddr, StringParameter.SOURCE_ADDR); PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_QUERY_SM, 0, sequenceNumber); buf.append(messageId); buf.append(sourceAddrTon); buf.append(sourceAddrNpi); buf.append(sourceAddr); return buf.toBytes(); } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#querySmResp(int, java.lang.String, * java.lang.String, byte, byte) */ public byte[] querySmResp(int sequenceNumber, String messageId, String finalDate, byte messageState, byte errorCode) throws PDUStringException { StringValidator.validateString(messageId, StringParameter.MESSAGE_ID); StringValidator.validateString(finalDate, StringParameter.FINAL_DATE); PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_QUERY_SM_RESP, 0, sequenceNumber); buf.append(messageId); buf.append(finalDate); buf.append(messageState); buf.append(errorCode); return buf.toBytes(); } // DELIVER_SM OPERATION /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#deliverSm(int, java.lang.String, byte, * byte, java.lang.String, byte, byte, java.lang.String, byte, byte, * byte, byte, byte, byte[], org.jsmpp.bean.OptionalParameter[]) */ public byte[] deliverSm(int sequenceNumber, String serviceType, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte destAddrTon, byte destAddrNpi, String destinationAddr, byte esmClass, byte protocolId, byte priorityFlag, byte registeredDelivery, byte dataCoding, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException { StringValidator.validateString(serviceType, StringParameter.SERVICE_TYPE); StringValidator.validateString(sourceAddr, StringParameter.SOURCE_ADDR); StringValidator.validateString(destinationAddr, StringParameter.DESTINATION_ADDR); StringValidator.validateString(shortMessage, StringParameter.SHORT_MESSAGE); PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_DELIVER_SM, 0, sequenceNumber); buf.append(serviceType); buf.append(sourceAddrTon); buf.append(sourceAddrNpi); buf.append(sourceAddr); buf.append(destAddrTon); buf.append(destAddrNpi); buf.append(destinationAddr); buf.append(esmClass); buf.append(protocolId); buf.append(priorityFlag); // buf.append(scheduleDeliveryTime); buf.append((String)null); // schedule delivery time // buf.append(validityPeriod); buf.append((String)null); // validity period buf.append(registeredDelivery); // buf.append(replaceIfPresent); buf.append((byte)0); // replace if present flag buf.append(dataCoding); // buf.append(smDefaultMsgId); buf.append((byte)0); // sm default msg id buf.append((byte)shortMessage.length); buf.append(shortMessage); buf.appendAll(optionalParameters); ; return buf.toBytes(); } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#deliverSmResp(int) */ public byte[] deliverSmResp(int sequenceNumber) { PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_DELIVER_SM_RESP, 0, sequenceNumber); buf.append((String)null); return buf.toBytes(); } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#dataSm(int, java.lang.String, byte, byte, * java.lang.String, byte, byte, java.lang.String, byte, byte, byte, * org.jsmpp.bean.OptionalParameter[]) */ public byte[] dataSm(int sequenceNumber, String serviceType, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte destAddrTon, byte destAddrNpi, String destinationAddr, byte esmClass, byte registeredDelivery, byte dataCoding, OptionalParameter... optionalParameters) throws PDUStringException { StringValidator.validateString(serviceType, StringParameter.SERVICE_TYPE); StringValidator.validateString(sourceAddr, StringParameter.SOURCE_ADDR); StringValidator.validateString(destinationAddr, StringParameter.DESTINATION_ADDR); PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_DATA_SM, 0, sequenceNumber); buf.append(serviceType); buf.append(sourceAddrTon); buf.append(sourceAddrNpi); buf.append(sourceAddr); buf.append(destAddrTon); buf.append(destAddrNpi); buf.append(destinationAddr); buf.append(esmClass); buf.append(registeredDelivery); buf.append(dataCoding); buf.appendAll(optionalParameters); return buf.toBytes(); } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUComposer#dataSmResp(int, java.lang.String, * org.jsmpp.bean.OptionalParameter[]) */ public byte[] dataSmResp(int sequenceNumber, String messageId, OptionalParameter... optionalParameters) throws PDUStringException { StringValidator.validateString(messageId, StringParameter.MESSAGE_ID); PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_DATA_SM_RESP, 0, sequenceNumber); buf.append(messageId); return buf.toBytes(); } public byte[] cancelSm(int sequenceNumber, String serviceType, String messageId, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte destAddrTon, byte destAddrNpi, String destinationAddr) throws PDUStringException { StringValidator.validateString(serviceType, StringParameter.SERVICE_TYPE); StringValidator.validateString(messageId, StringParameter.MESSAGE_ID); StringValidator.validateString(sourceAddr, StringParameter.SOURCE_ADDR); StringValidator.validateString(destinationAddr, StringParameter.DESTINATION_ADDR); PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_CANCEL_SM, 0, sequenceNumber); buf.append(serviceType); buf.append(messageId); buf.append(sourceAddrTon); buf.append(sourceAddrNpi); buf.append(sourceAddr); buf.append(destAddrTon); buf.append(destAddrNpi); buf.append(destinationAddr); return buf.toBytes(); } public byte[] cancelSmResp(int sequenceNumber) { byte[] b = composeHeader(SMPPConstant.CID_CANCEL_SM_RESP, SMPPConstant.STAT_ESME_ROK, sequenceNumber); return b; } public byte[] replaceSm(int sequenceNumber, String messageId, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, String scheduleDeliveryTime, String validityPeriod, byte registeredDelivery, byte smDefaultMsgId, byte[] shortMessage) throws PDUStringException { StringValidator.validateString(sourceAddr, StringParameter.SOURCE_ADDR); StringValidator.validateString(scheduleDeliveryTime, StringParameter.SCHEDULE_DELIVERY_TIME); StringValidator.validateString(validityPeriod, StringParameter.VALIDITY_PERIOD); StringValidator.validateString(shortMessage, StringParameter.SHORT_MESSAGE); PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_REPLACE_SM, 0, sequenceNumber); buf.append(messageId); buf.append(sourceAddrTon); buf.append(sourceAddrNpi); buf.append(sourceAddr); buf.append(scheduleDeliveryTime); buf.append(validityPeriod); buf.append(registeredDelivery); buf.append(smDefaultMsgId); buf.append((byte)shortMessage.length); buf.append(shortMessage); return buf.toBytes(); } public byte[] replaceSmResp(int sequenceNumber) { return composeHeader(SMPPConstant.CID_REPLACE_SM_RESP, 0, sequenceNumber); } public byte[] submitMulti(int sequenceNumber, String serviceType, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, DestinationAddress[] destinationAddresses, byte esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, byte registeredDelivery, byte replaceIfPresentFlag, byte dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException, InvalidNumberOfDestinationsException { StringValidator.validateString(serviceType, StringParameter.SERVICE_TYPE); StringValidator.validateString(sourceAddr, StringParameter.SOURCE_ADDR); StringValidator.validateString(scheduleDeliveryTime, StringParameter.SCHEDULE_DELIVERY_TIME); StringValidator.validateString(validityPeriod, StringParameter.VALIDITY_PERIOD); StringValidator.validateString(shortMessage, StringParameter.SHORT_MESSAGE); if (destinationAddresses.length > 255) { throw new InvalidNumberOfDestinationsException( "Number of destination is invalid. Should be no more than 255. Actual number is " + destinationAddresses, destinationAddresses.length); } PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_SUBMIT_MULTI, 0, sequenceNumber); buf.append(serviceType); buf.append(sourceAddrTon); buf.append(sourceAddrNpi); buf.append(sourceAddr); buf.append((byte)destinationAddresses.length); for (DestinationAddress destAddr : destinationAddresses) { buf.append(destAddr.getFlag().getValue()); if (destAddr instanceof Address) { Address addr = (Address)destAddr; StringValidator.validateString(addr.getAddress(), StringParameter.DESTINATION_ADDR); buf.append(addr.getTon()); buf.append(addr.getNpi()); buf.append(addr.getAddress()); } else if (destAddr instanceof DistributionList) { DistributionList dl = (DistributionList)destAddr; StringValidator.validateString(dl.getName(), StringParameter.DL_NAME); } else { logger.warn("Unknown destination address flag: " + destAddr.getClass()); } } buf.append(esmClass); buf.append(protocolId); buf.append(priorityFlag); buf.append(scheduleDeliveryTime); buf.append(validityPeriod); buf.append(registeredDelivery); buf.append(replaceIfPresentFlag); buf.append(dataCoding); buf.append(smDefaultMsgId); buf.append((byte)shortMessage.length); buf.append(shortMessage); buf.appendAll(optionalParameters); return buf.toBytes(); } public byte[] submitMultiResp(int sequenceNumber, String messageId, UnsuccessDelivery... unsuccessDeliveries) throws PDUStringException { StringValidator.validateString(messageId, StringParameter.MESSAGE_ID); PDUByteBuffer buf = new PDUByteBuffer( SMPPConstant.CID_SUBMIT_MULTI_RESP, 0, sequenceNumber); buf.append(messageId); buf.append((byte)unsuccessDeliveries.length); // no_unsuccess for (UnsuccessDelivery delivery : unsuccessDeliveries) { StringValidator.validateString(delivery.getDestinationAddress() .getAddress(), StringParameter.DESTINATION_ADDR); Address destAddr = delivery.getDestinationAddress(); buf.append(destAddr.getTon()); buf.append(destAddr.getNpi()); buf.append(destAddr.getAddress()); buf.append(delivery.getErrorStatusCode()); } return buf.toBytes(); } public byte[] alertNotification(int sequenceNumber, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte esmeAddrTon, byte esmeAddrNpi, String esmeAddr, OptionalParameter... optionalParameters) throws PDUStringException { StringValidator.validateString(sourceAddr, StringParameter.SOURCE_ADDR); StringValidator.validateString(esmeAddr, StringParameter.ESME_ADDR); PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_ALERT_NOTIFICATION, 0, sequenceNumber); buf.append(sourceAddrTon); buf.append(sourceAddrNpi); buf.append(sourceAddr); buf.append(esmeAddrTon); buf.append(esmeAddrNpi); buf.append(esmeAddr); buf.appendAll(optionalParameters); return buf.toBytes(); } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/DefaultDecomposer.java000066400000000000000000000703571246113105100244540ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.jsmpp.InvalidNumberOfDestinationsException; import org.jsmpp.PDUStringException; import org.jsmpp.bean.Address; import org.jsmpp.bean.AlertNotification; import org.jsmpp.bean.Bind; import org.jsmpp.bean.BindResp; import org.jsmpp.bean.CancelSm; import org.jsmpp.bean.CancelSmResp; import org.jsmpp.bean.Command; import org.jsmpp.bean.DataSm; import org.jsmpp.bean.DataSmResp; import org.jsmpp.bean.DeliverSm; import org.jsmpp.bean.DeliverSmResp; import org.jsmpp.bean.DeliveryReceipt; import org.jsmpp.bean.DestinationAddress; import org.jsmpp.bean.DistributionList; import org.jsmpp.bean.EnquireLink; import org.jsmpp.bean.EnquireLinkResp; import org.jsmpp.bean.GenericNack; import org.jsmpp.bean.MessageState; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.OptionalParameters; import org.jsmpp.bean.Outbind; import org.jsmpp.bean.QuerySm; import org.jsmpp.bean.QuerySmResp; import org.jsmpp.bean.ReplaceSm; import org.jsmpp.bean.ReplaceSmResp; import org.jsmpp.bean.SubmitMulti; import org.jsmpp.bean.SubmitMultiResp; import org.jsmpp.bean.SubmitSm; import org.jsmpp.bean.SubmitSmResp; import org.jsmpp.bean.Unbind; import org.jsmpp.bean.UnbindResp; import org.jsmpp.bean.UnsuccessDelivery; import org.jsmpp.bean.DestinationAddress.Flag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Default implementation of SMPP PDU PDUDecomposer. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class DefaultDecomposer implements PDUDecomposer { private static final Logger logger = LoggerFactory .getLogger(DefaultDecomposer.class); private static final PDUDecomposer instance = new DefaultDecomposer(); public static final PDUDecomposer getInstance() { return instance; } /** * Default constructor. */ public DefaultDecomposer() { } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#header(byte[]) */ public Command header(byte[] b) { Command pdu = new Command(); assignHeader(pdu, b); return pdu; } // BIND OPERATION /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#bind(byte[]) */ public Bind bind(byte[] b) throws PDUStringException { Bind req = new Bind(); SequentialBytesReader reader = new SequentialBytesReader(b); assignHeader(req, reader); req.setSystemId(reader.readCString()); StringValidator.validateString(req.getSystemId(), StringParameter.SYSTEM_ID); req.setPassword(reader.readCString()); StringValidator.validateString(req.getPassword(), StringParameter.PASSWORD); req.setSystemType(reader.readCString()); StringValidator.validateString(req.getSystemType(), StringParameter.SYSTEM_TYPE); req.setInterfaceVersion(reader.readByte()); req.setAddrTon(reader.readByte()); req.setAddrNpi(reader.readByte()); req.setAddressRange(reader.readCString()); StringValidator.validateString(req.getAddressRange(), StringParameter.ADDRESS_RANGE); return req; } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#bindResp(byte[]) */ public BindResp bindResp(byte[] b) throws PDUStringException { BindResp resp = new BindResp(); SequentialBytesReader reader = new SequentialBytesReader(b); assignHeader(resp, reader); if (resp.getCommandLength() > 16 && resp.getCommandStatus() == 0) { resp.setSystemId(reader.readCString()); StringValidator.validateString(resp.getSystemId(), StringParameter.SYSTEM_ID); resp.setOptionalParameters(readOptionalParameters(reader)); } return resp; } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#unbind(byte[]) */ public Unbind unbind(byte[] b) { Unbind req = new Unbind(); assignHeader(req, b); return req; } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#unbindResp(byte[]) */ public UnbindResp unbindResp(byte[] b) { UnbindResp resp = new UnbindResp(); assignHeader(resp, b); return resp; } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#outbind(byte[]) */ public Outbind outbind(byte[] b) throws PDUStringException { Outbind req = new Outbind(); SequentialBytesReader reader = new SequentialBytesReader(b); assignHeader(req, reader); req.setSystemId(reader.readCString()); StringValidator.validateString(req.getSystemId(), StringParameter.SYSTEM_ID); req.setPassword(reader.readCString()); StringValidator.validateString(req.getPassword(), StringParameter.PASSWORD); return req; } // ENQUIRE_LINK OPERATION /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#enquireLink(byte[]) */ public EnquireLink enquireLink(byte[] b) { EnquireLink req = new EnquireLink(); assignHeader(req, b); return req; } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#enquireLinkResp(byte[]) */ public EnquireLinkResp enquireLinkResp(byte[] b) { EnquireLinkResp resp = new EnquireLinkResp(); assignHeader(resp, b); return resp; } // GENERICK_NACK OPERATION /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#genericNack(byte[]) */ public GenericNack genericNack(byte[] b) { GenericNack req = new GenericNack(); assignHeader(req, b); return req; } // SUBMIT_SM OPERATION /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#submitSm(byte[]) */ public SubmitSm submitSm(byte[] b) throws PDUStringException { SubmitSm req = new SubmitSm(); SequentialBytesReader reader = new SequentialBytesReader(b); assignHeader(req, reader); req.setServiceType(reader.readCString()); StringValidator.validateString(req.getServiceType(), StringParameter.SERVICE_TYPE); req.setSourceAddrTon(reader.readByte()); req.setSourceAddrNpi(reader.readByte()); req.setSourceAddr(reader.readCString()); StringValidator.validateString(req.getSourceAddr(), StringParameter.SOURCE_ADDR); req.setDestAddrTon(reader.readByte()); req.setDestAddrNpi(reader.readByte()); req.setDestAddress(reader.readCString()); StringValidator.validateString(req.getDestAddress(), StringParameter.DESTINATION_ADDR); req.setEsmClass(reader.readByte()); req.setProtocolId(reader.readByte()); req.setPriorityFlag(reader.readByte()); req.setScheduleDeliveryTime(reader.readCString()); StringValidator.validateString(req.getScheduleDeliveryTime(), StringParameter.SCHEDULE_DELIVERY_TIME); req.setValidityPeriod(reader.readCString()); StringValidator.validateString(req.getValidityPeriod(), StringParameter.VALIDITY_PERIOD); req.setRegisteredDelivery(reader.readByte()); req.setReplaceIfPresent(reader.readByte()); req.setDataCoding(reader.readByte()); req.setSmDefaultMsgId(reader.readByte()); byte smLength = reader.readByte(); // req.setShortMessage(reader.readString(req.getSmLength())); req.setShortMessage(reader.readBytes(smLength)); StringValidator.validateString(req.getShortMessage(), StringParameter.SHORT_MESSAGE); req.setOptionalParametes(readOptionalParameters(reader)); return req; } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#submitSmResp(byte[]) */ public SubmitSmResp submitSmResp(byte[] b) throws PDUStringException { SubmitSmResp resp = new SubmitSmResp(); SequentialBytesReader reader = new SequentialBytesReader(b); assignHeader(resp, reader); if (resp.getCommandLength() > 16 && resp.getCommandStatus() == 0) { resp.setMessageId(reader.readCString()); StringValidator.validateString(resp.getMessageId(), StringParameter.MESSAGE_ID); } return resp; } // QUERY_SM OPERATION /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#querySm(byte[]) */ public QuerySm querySm(byte[] b) throws PDUStringException { QuerySm req = new QuerySm(); SequentialBytesReader reader = new SequentialBytesReader(b); assignHeader(req, reader); req.setMessageId(reader.readCString()); StringValidator.validateString(req.getMessageId(), StringParameter.MESSAGE_ID); req.setSourceAddrTon(reader.readByte()); req.setSourceAddrNpi(reader.readByte()); req.setSourceAddr(reader.readCString()); StringValidator.validateString(req.getSourceAddr(), StringParameter.SOURCE_ADDR); return req; } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#querySmResp(byte[]) */ public QuerySmResp querySmResp(byte[] b) throws PDUStringException { QuerySmResp resp = new QuerySmResp(); SequentialBytesReader reader = new SequentialBytesReader(b); assignHeader(resp, reader); if (resp.getCommandLength() > 16 && resp.getCommandStatus() == 0) { resp.setMessageId(reader.readCString()); StringValidator.validateString(resp.getMessageId(), StringParameter.MESSAGE_ID); resp.setFinalDate(reader.readCString()); StringValidator.validateString(resp.getFinalDate(), StringParameter.FINAL_DATE); resp.setMessageState(MessageState.valueOf(reader.readByte())); resp.setErrorCode(reader.readByte()); } return resp; } // DELIVER_SM OPERATION /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#deliverSm(byte[]) */ public DeliverSm deliverSm(byte[] b) throws PDUStringException { DeliverSm req = new DeliverSm(); SequentialBytesReader reader = new SequentialBytesReader(b); assignHeader(req, reader); req.setServiceType(reader.readCString()); StringValidator.validateString(req.getServiceType(), StringParameter.SERVICE_TYPE); req.setSourceAddrTon(reader.readByte()); req.setSourceAddrNpi(reader.readByte()); req.setSourceAddr(reader.readCString()); StringValidator.validateString(req.getSourceAddr(), StringParameter.SOURCE_ADDR); req.setDestAddrTon(reader.readByte()); req.setDestAddrNpi(reader.readByte()); req.setDestAddress(reader.readCString()); StringValidator.validateString(req.getDestAddress(), StringParameter.DESTINATION_ADDR); req.setEsmClass(reader.readByte()); req.setProtocolId(reader.readByte()); req.setPriorityFlag(reader.readByte()); // scheduleDeliveryTime should be null of c-octet string req.setScheduleDeliveryTime(reader.readCString()); StringValidator.validateString(req.getScheduleDeliveryTime(), StringParameter.SCHEDULE_DELIVERY_TIME); // validityPeriod should be null of c-octet string req.setValidityPeriod(reader.readCString()); StringValidator.validateString(req.getValidityPeriod(), StringParameter.VALIDITY_PERIOD); req.setRegisteredDelivery(reader.readByte()); // replaceIfPresent should be null req.setReplaceIfPresent(reader.readByte()); req.setDataCoding(reader.readByte()); // smDefaultMsgId should be null req.setSmDefaultMsgId(reader.readByte()); byte smLength = reader.readByte(); req.setShortMessage(reader.readBytes(smLength)); StringValidator.validateString(req.getShortMessage(), StringParameter.SHORT_MESSAGE); req.setOptionalParametes(readOptionalParameters(reader)); return req; } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#deliverSmResp(byte[]) */ public DeliverSmResp deliverSmResp(byte[] b) { DeliverSmResp resp = new DeliverSmResp(); SequentialBytesReader reader = new SequentialBytesReader(b); assignHeader(resp, reader); // ignore the message_id, because it unused. return resp; } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#deliveryReceipt(java.lang.String) */ public DeliveryReceipt deliveryReceipt(String data) throws InvalidDeliveryReceiptException { /* * id:IIIIIIIIII sub:SSS dlvrd:DDD submit date:YYMMDDhhmm done * date:YYMMDDhhmm stat:DDDDDDD err:E Text: .......... */ try { DeliveryReceipt delRec = new DeliveryReceipt(); delRec.setId(getDeliveryReceiptValue(DeliveryReceipt.DELREC_ID, data)); delRec.setSubmitted(Integer.parseInt(getDeliveryReceiptValue( DeliveryReceipt.DELREC_SUB, data))); delRec.setDelivered(Integer.parseInt(getDeliveryReceiptValue( DeliveryReceipt.DELREC_DLVRD, data))); delRec.setSubmitDate(string2Date(getDeliveryReceiptValue( DeliveryReceipt.DELREC_SUBMIT_DATE, data))); delRec.setDoneDate(string2Date(getDeliveryReceiptValue( DeliveryReceipt.DELREC_DONE_DATE, data))); delRec.setFinalStatus(DeliveryReceiptState .getByName(getDeliveryReceiptValue( DeliveryReceipt.DELREC_STAT, data))); delRec.setError(getDeliveryReceiptValue(DeliveryReceipt.DELREC_ERR, data)); delRec.setText(getDeliveryReceiptTextValue(data)); return delRec; } catch (Exception e) { throw new InvalidDeliveryReceiptException( "There is an error found when parsing delivery receipt", e); } } /* * (non-Javadoc) * * @see org.jsmpp.util.PDUDecomposer#deliveryReceipt(byte[]) */ public DeliveryReceipt deliveryReceipt(byte[] data) throws InvalidDeliveryReceiptException { return deliveryReceipt(new String(data)); } public DataSm dataSm(byte[] data) throws PDUStringException { DataSm req = new DataSm(); SequentialBytesReader reader = new SequentialBytesReader(data); assignHeader(req, reader); req.setServiceType(reader.readCString()); StringValidator.validateString(req.getServiceType(), StringParameter.SERVICE_TYPE); req.setSourceAddrTon(reader.readByte()); req.setSourceAddrNpi(reader.readByte()); req.setSourceAddr(reader.readCString()); StringValidator.validateString(req.getSourceAddr(), StringParameter.SOURCE_ADDR); req.setDestAddrTon(reader.readByte()); req.setDestAddrNpi(reader.readByte()); req.setDestAddress(reader.readCString()); StringValidator.validateString(req.getDestAddress(), StringParameter.DESTINATION_ADDR); req.setEsmClass(reader.readByte()); req.setRegisteredDelivery(reader.readByte()); req.setDataCoding(reader.readByte()); req.setOptionalParametes(readOptionalParameters(reader)); return req; } public DataSmResp dataSmResp(byte[] data) throws PDUStringException { DataSmResp resp = new DataSmResp(); SequentialBytesReader reader = new SequentialBytesReader(data); assignHeader(resp, reader); if (resp.getCommandLength() > 16 && resp.getCommandStatus() == 0) { resp.setMessageId(reader.readCString()); StringValidator.validateString(resp.getMessageId(), StringParameter.MESSAGE_ID); } return resp; } public CancelSm cancelSm(byte[] data) throws PDUStringException { CancelSm req = new CancelSm(); SequentialBytesReader reader = new SequentialBytesReader(data); assignHeader(req, reader); req.setServiceType(reader.readCString()); StringValidator.validateString(req.getServiceType(), StringParameter.SERVICE_TYPE); req.setMessageId(reader.readCString()); StringValidator.validateString(req.getMessageId(), StringParameter.MESSAGE_ID); req.setSourceAddrTon(reader.readByte()); req.setSourceAddrNpi(reader.readByte()); req.setSourceAddr(reader.readCString()); StringValidator.validateString(req.getSourceAddr(), StringParameter.SOURCE_ADDR); req.setDestAddrTon(reader.readByte()); req.setDestAddrNpi(reader.readByte()); req.setDestinationAddress(reader.readCString()); StringValidator.validateString(req.getDestinationAddress(), StringParameter.DESTINATION_ADDR); return req; } public CancelSmResp cancelSmResp(byte[] data) { CancelSmResp resp = new CancelSmResp(); assignHeader(resp, data); return resp; } public SubmitMulti submitMulti(byte[] data) throws PDUStringException, InvalidNumberOfDestinationsException { SubmitMulti req = new SubmitMulti(); SequentialBytesReader reader = new SequentialBytesReader(data); assignHeader(req, reader); req.setServiceType(reader.readCString()); StringValidator.validateString(req.getServiceType(), StringParameter.SERVICE_TYPE); req.setSourceAddrTon(reader.readByte()); req.setSourceAddrNpi(reader.readByte()); req.setSourceAddr(reader.readCString()); StringValidator.validateString(req.getSourceAddr(), StringParameter.SOURCE_ADDR); int totalDest = 0xff & reader.readByte(); if (totalDest > 255) { throw new InvalidNumberOfDestinationsException( "Number of destination is invalid. Should be no more than 255. Actual number is " + totalDest, totalDest); } DestinationAddress[] destAddresses = new DestinationAddress[totalDest]; for (int i = 0; i < totalDest; i++) { byte flag = reader.readByte(); if (flag == Flag.SME_ADDRESS.getValue()) { byte ton = reader.readByte(); byte npi = reader.readByte(); String addr = reader.readCString(); StringValidator.validateString(addr, StringParameter.DESTINATION_ADDR); Address destAddr = new Address(ton, npi, addr); destAddresses[i] = destAddr; } else if (flag == Flag.DISTRIBUTION_LIST.getValue()) { destAddresses[i] = new DistributionList(reader.readCString()); } else { logger.warn("Unknown destination address flag: " + flag); } } req.setDestAddresses(destAddresses); req.setEsmClass(reader.readByte()); req.setProtocolId(reader.readByte()); req.setPriorityFlag(reader.readByte()); req.setScheduleDeliveryTime(reader.readCString()); StringValidator.validateString(req.getScheduleDeliveryTime(), StringParameter.SCHEDULE_DELIVERY_TIME); req.setValidityPeriod(reader.readCString()); StringValidator.validateString(req.getValidityPeriod(), StringParameter.VALIDITY_PERIOD); req.setRegisteredDelivery(reader.readByte()); req.setReplaceIfPresentFlag(reader.readByte()); req.setDataCoding(reader.readByte()); req.setSmDefaultMsgId(reader.readByte()); byte smLength = reader.readByte(); req.setShortMessage(reader.readBytes(smLength)); StringValidator.validateString(req.getShortMessage(), StringParameter.SHORT_MESSAGE); req.setOptionalParameters(readOptionalParameters(reader)); return req; } public SubmitMultiResp submitMultiResp(byte[] data) throws PDUStringException { SubmitMultiResp resp = new SubmitMultiResp(); SequentialBytesReader reader = new SequentialBytesReader(data); assignHeader(resp, reader); resp.setMessageId(reader.readCString()); StringValidator.validateString(resp.getMessageId(), StringParameter.MESSAGE_ID); int noUnsuccess = 0xff & reader.readByte(); UnsuccessDelivery[] unsuccessSmes = new UnsuccessDelivery[noUnsuccess]; for (int i = 0; i < noUnsuccess; i++) { byte ton = reader.readByte(); byte npi = reader.readByte(); String addr = reader.readCString(); StringValidator.validateString(addr, StringParameter.DESTINATION_ADDR); int errorStatusCode = reader.readInt(); unsuccessSmes[i] = new UnsuccessDelivery(ton, npi, addr, errorStatusCode); } resp.setUnsuccessSmes(unsuccessSmes); return resp; } public ReplaceSm replaceSm(byte[] data) throws PDUStringException { ReplaceSm req = new ReplaceSm(); SequentialBytesReader reader = new SequentialBytesReader(data); assignHeader(req, reader); req.setMessageId(reader.readCString()); StringValidator.validateString(req.getMessageId(), StringParameter.MESSAGE_ID); req.setSourceAddrTon(reader.readByte()); req.setSourceAddrNpi(reader.readByte()); req.setSourceAddr(reader.readCString()); StringValidator.validateString(req.getSourceAddr(), StringParameter.SOURCE_ADDR); req.setScheduleDeliveryTime(reader.readCString()); StringValidator.validateString(req.getScheduleDeliveryTime(), StringParameter.SCHEDULE_DELIVERY_TIME); req.setValidityPeriod(reader.readCString()); StringValidator.validateString(req.getValidityPeriod(), StringParameter.VALIDITY_PERIOD); req.setSmDefaultMsgId(reader.readByte()); byte smLength = reader.readByte(); req.setShortMessage(reader.readBytes(smLength)); StringValidator.validateString(req.getShortMessage(), StringParameter.SHORT_MESSAGE); return req; } public ReplaceSmResp replaceSmResp(byte[] data) { ReplaceSmResp resp = new ReplaceSmResp(); assignHeader(resp, data); return resp; } public AlertNotification alertNotification(byte[] data) throws PDUStringException { AlertNotification req = new AlertNotification(); SequentialBytesReader reader = new SequentialBytesReader(data); assignHeader(req, reader); req.setSourceAddrTon(reader.readByte()); req.setSourceAddrNpi(reader.readByte()); req.setSourceAddr(reader.readCString()); StringValidator.validateString(req.getSourceAddr(), StringParameter.SOURCE_ADDR); req.setEsmeAddrTon(reader.readByte()); req.setEsmeAddrNpi(reader.readByte()); /* * No validation on esme_addr. * There is no response to alert_notificaion command, so error will be * ignored. */ req.setEsmeAddr(reader.readCString()); req.setOptionalParameters(readOptionalParameters(reader)); return req; } private OptionalParameter[] readOptionalParameters( SequentialBytesReader reader) { if (!reader.hasMoreBytes()) return null; List params = new ArrayList(); while (reader.hasMoreBytes()) { short tag = reader.readShort(); short length = reader.readShort(); byte[] content = reader.readBytes(length); params.add(OptionalParameters.deserialize(tag, content)); } return params.toArray(new OptionalParameter[params.size()]); } /** * YYMMDDhhmm where: *
    *
  • YY = last two digits of the year (00-99)
  • *
  • MM = month (01-12)
  • *
  • DD = day (01-31)
  • *
  • hh = hour (00-23)
  • *
  • mm = minute (00-59)
  • *
* * Java format is (yyMMddHHmm). * * @param date in String format. * @return * @throws NumberFormatException if there is contains non number on * date parameter. * @throws IndexOutOfBoundsException if the date length in String * format is less than 10. */ private static Date string2Date(String date) { int year = Integer.parseInt(date.substring(0, 2)); int month = Integer.parseInt(date.substring(2, 4)); int day = Integer.parseInt(date.substring(4, 6)); int hour = Integer.parseInt(date.substring(6, 8)); int minute = Integer.parseInt(date.substring(8, 10)); Calendar cal = Calendar.getInstance(); cal.set(convertTwoDigitYear(year), month - 1, day, hour, minute, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } private static int convertTwoDigitYear(int year) { if (year >=0 && year <= 37) { return 2000 + year; } else if (year >= 38 && year <= 99) { return 1900 + year; } else { // should never happen return year; } } /** * Get the delivery receipt attribute value. * * @param attrName is the attribute name. * @param source the original source id:IIIIIIIIII sub:SSS dlvrd:DDD submit * date:YYMMDDhhmm done date:YYMMDDhhmm stat:DDDDDDD err:E * Text:.................... * @return the value of specified attribute. * @throws IndexOutOfBoundsException */ private static String getDeliveryReceiptValue(String attrName, String source) throws IndexOutOfBoundsException { String tmpAttr = attrName + ":"; int startIndex = source.indexOf(tmpAttr); if (startIndex < 0) return null; startIndex = startIndex + tmpAttr.length(); int endIndex = source.indexOf(" ", startIndex); if (endIndex > 0) return source.substring(startIndex, endIndex); return source.substring(startIndex); } /** * @param source * @return * @throws IndexOutOfBoundsException */ private static String getDeliveryReceiptTextValue(String source) { String tmpAttr = DeliveryReceipt.DELREC_TEXT + ":"; int startIndex = source.indexOf(tmpAttr); if (startIndex < 0) { tmpAttr = DeliveryReceipt.DELREC_TEXT.toLowerCase() + ":"; startIndex = source.indexOf(tmpAttr); } if (startIndex < 0) { return null; } startIndex = startIndex + tmpAttr.length(); return source.substring(startIndex); } private static void assignHeader(Command pdu, SequentialBytesReader seqBytesReader) { int commandLength = seqBytesReader.readInt(); if (seqBytesReader.getBytes().length != commandLength) logger.error("SYSTEM BUGS, the command_length (" + commandLength + ") not equals with the byte array length (" + seqBytesReader.getBytes().length + ")"); pdu.setCommandLength(commandLength); pdu.setCommandId(seqBytesReader.readInt()); pdu.setCommandStatus(seqBytesReader.readInt()); pdu.setSequenceNumber(seqBytesReader.readInt()); } private static void assignHeader(Command pdu, byte[] bytes) { assignHeader(pdu, new SequentialBytesReader(bytes)); } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/DeliveryReceiptState.java000066400000000000000000000032401246113105100251320ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * @author uudashr * @version 1.0 * @since 1.0 * */ public enum DeliveryReceiptState { /** * DELIVERED */ DELIVRD(1), /** * EXPIRED */ EXPIRED(2), /** * DELETED */ DELETED(3), /** * UNDELIVERABLE */ UNDELIV(4), /** * ACCEPTED */ ACCEPTD(5), /** * UNKNOWN */ UNKNOWN(6), /** * REJECTED */ REJECTD(7); private int value; private DeliveryReceiptState(int value) { this.value = value; } public static DeliveryReceiptState getByName(String name) { return valueOf(DeliveryReceiptState.class, name); } public static DeliveryReceiptState valueOf(int value) throws IllegalArgumentException { for (DeliveryReceiptState item : values()) { if (item.value() == value) { return item; } } throw new IllegalArgumentException( "No enum const DeliveryReceiptState with value " + value); } public int value() { return value; } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/DumbCapacityPolicy.java000066400000000000000000000017731246113105100245700ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * It's a dumb capacity policy. It calculate nothing, just return the new * capacity same as requeiredCapacity. * * @author uudashr * */ public class DumbCapacityPolicy implements CapacityPolicy { /* (non-Javadoc) * @see org.jsmpp.util.CapacityPolicy#ensureCapacity(int, int) */ public int ensureCapacity(int requiredCapacity, int currentCapacity) { return requiredCapacity; } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/HexUtil.java000066400000000000000000000112361246113105100224200ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import java.util.Arrays; /** * The Hex utility. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class HexUtil { private static final char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** * Convert the string to hex string value. * * @param data is case sensitive. * @return the hex string representation of string. */ public static String convertStringToHexString(String data) { return conventBytesToHexString(data.getBytes()); } /** * Convert bytes to hex string. * * @param data is the bytes. * @return the hex string representation of bytes. */ public static String conventBytesToHexString(byte[] data) { return convertBytesToHexString(data, 0, data.length); } // /** * Convert bytes to hex string value (using Big-Endian rule). * * @param data is the bytes. * @param offset is the offset. * @param length is the length. * @return the hex string representation of bytes. */ public static String convertBytesToHexString(byte[] data, int offset, int length) { StringBuffer sBuf = new StringBuffer(); // System.err.println("converBytesToHexString"); for (int i = offset; i < length; i++) { /* * System.err.println("data[" + i + "] = " + data[i]); * System.err.println(hexChar[(data[i] >> 4) & 0xf]); * System.err.println(hexChar[data[i] & 0xf]); */ sBuf.append(hexChar[(data[i] >> 4) & 0xf]); sBuf.append(hexChar[data[i] & 0xf]); /* * sBuf.append(hexChar[(data[i] >> 4) & 0xf]); * sBuf.append(hexChar[data[i]& 0xf]); */ // sBuf.append(Integer.toHexString(data[i])); } return sBuf.toString(); } /** * Convert the hex string to string. * * @param hexString is the hex string. * @return the string value that converted from hex string. */ public static String convertHexStringToString(String hexString) { String uHexString = hexString.toLowerCase(); StringBuffer sBuf = new StringBuffer(); for (int i = 0; i < uHexString.length(); i = i + 2) { char c = (char)Integer.parseInt(uHexString.substring(i, i + 2), 16); sBuf.append(c); } return sBuf.toString(); } /** * Convert the hex string to bytes. * * @param hexString is the hex string. * @return the bytes value that converted from the hex string. */ public static byte[] convertHexStringToBytes(String hexString) { return convertHexStringToBytes(hexString, 0, hexString.length()); } /** * Convert the hex string to bytes. * * @param hexString is the hex string. * @param offset is the offset. * @param endIndex is the end index. * @return the bytes value that converted from the hex string. */ public static byte[] convertHexStringToBytes(String hexString, int offset, int endIndex) { byte[] data; String realHexString = hexString.substring(offset, endIndex) .toLowerCase(); if ((realHexString.length() % 2) == 0) data = new byte[realHexString.length() / 2]; else data = new byte[(int)Math.ceil(realHexString.length() / 2d)]; int j = 0; char[] tmp; for (int i = 0; i < realHexString.length(); i += 2) { try { tmp = realHexString.substring(i, i + 2).toCharArray(); } catch (StringIndexOutOfBoundsException siob) { // it only contains one character, so add "0" string tmp = (realHexString.substring(i) + "0").toCharArray(); } data[j] = (byte)((Arrays.binarySearch(hexChar, tmp[0]) & 0xf) << 4); data[j++] |= (byte)(Arrays.binarySearch(hexChar, tmp[1]) & 0xf); } for (int i = realHexString.length(); i > 0; i -= 2) { } return data; } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/IntUtil.java000066400000000000000000000024221246113105100224230ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * The int util. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class IntUtil { public static String to4DigitString(int value) { return toNDigitString(value, 4); } public static String to2DigitString(int value) { return toNDigitString(value, 2); } public static String toNDigitString(int value, int digitLength) { StringBuffer sBuf = new StringBuffer(String.valueOf(value)); while (sBuf.length() < digitLength) sBuf.insert(0, "0"); return sBuf.toString(); } public static final String toHexString(int value) { return HexUtil.conventBytesToHexString(OctetUtil.intToBytes(value)); } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/InvalidDeliveryReceiptException.java000066400000000000000000000021131246113105100273150ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * This exception is throw if there is an invalid format on delivery receipt * content. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class InvalidDeliveryReceiptException extends Exception { private static final long serialVersionUID = 4069256615018999757L; public InvalidDeliveryReceiptException(String message) { super(message); } public InvalidDeliveryReceiptException(String message, Exception cause) { super(message, cause); } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/MessageIDGenerator.java000066400000000000000000000004401246113105100245010ustar00rootroot00000000000000package org.jsmpp.util; /** * Is the message_id generator. * * @author uudashr * @version 1.0 * @since 1.0 * */ public interface MessageIDGenerator { /** * Generate message-id, max 65 C-Octet String. * @return the generated message id. */ MessageId newMessageId(); } jsmpp-2.1.2/src/main/java/org/jsmpp/util/MessageId.java000066400000000000000000000041751246113105100227030ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import org.jsmpp.PDUStringException; /** * This class is wrap simple {@link String} value as message_id. The main * purpose is the creation of the value will be validated as proper message_id. * * @author uudashr * */ public class MessageId { private final String value; /** * Construct MessageId with specified value. * * @param value is the message_id as String. * @throws PDUStringException */ public MessageId(String value) throws PDUStringException { StringValidator.validateString(value, StringParameter.MESSAGE_ID); this.value = value; } /** * Get the message_id value. * * @return the value of message_id. */ public String getValue() { return value; } @Override public String toString() { return value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final MessageId other = (MessageId)obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/OctetUtil.java000066400000000000000000000055061246113105100227550ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * The octet util. * * @author uudashr * @version 1.0 * @version 1.0 * */ public class OctetUtil { /** * Convert integer (4 octets) value to bytes. * * @param value as 4 bytes representing integer in bytes. * @return */ public static byte[] intToBytes(int value) { byte[] result = new byte[4]; result[0] = (byte)(value >> 24 & 0xff); result[1] = (byte)(value >> 16 & 0xff); result[2] = (byte)(value >> 8 & 0xff); result[3] = (byte)(value & 0xff); return result; } /** * Convert integer (2 octets) value to bytes. * * @param value * @return */ public static byte[] shortToBytes(short value) { byte[] result = new byte[2]; result[0] = (byte)(value >> 8 & 0xff); result[1] = (byte)(value & 0xff); return result; } /** * 32 bit. * * @param bytes * @return */ public static int bytesToInt(byte[] bytes) { return bytesToInt(bytes, 0); } /** * 32 bit. * * @param bytes * @param offset * @return */ public static int bytesToInt(byte[] bytes, int offset) { // int result = 0x00000000; int length = 0; if (bytes.length - offset < 4) // maximum byte size for int data type // is 4 length = bytes.length - offset; else length = 4; int end = offset + length; for (int i = 0; i < length; i++) { // result |= bytes[end - i - 1] << (8 * i); result |= (bytes[end - i - 1] & 0xff) << (8 * i); // TODO uudashr: CHECK FOR IMPROVEMENT } return result; } /** * 16 bit. * * @param bytes * @return */ public static short bytesToShort(byte[] bytes) { return bytesToShort(bytes, 0); } /** * 16 bit. * * @param bytes * @param offset * @return */ public static short bytesToShort(byte[] bytes, int offset) { short result = 0x0000; int end = offset + 2; for (int i = 0; i < 2; i++) { result |= (bytes[end - i - 1] & 0xff) << (8 * i); } return result; } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/PDUByteBuffer.java000066400000000000000000000143511246113105100234450ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import org.jsmpp.bean.OptionalParameter; /** * Utility to compose the PDU bytes. The size of the buffer is depends to the * entities appended to the buffer. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class PDUByteBuffer { private static CapacityPolicy DEFAULT_CAPACITY_POLICY = new SimpleCapacityPolicy(); private CapacityPolicy capacityPolicy; private byte[] bytes; private int bytesLength; /** * Construct with specified command_id, command_status, and sequence_number. * * @param commandId is the command_id. * @param commandStatus is the command_status. * @param sequenceNumber is the sequence_number. */ public PDUByteBuffer(int commandId, int commandStatus, int sequenceNumber) { this(commandId, commandStatus, sequenceNumber, DEFAULT_CAPACITY_POLICY); } /** * Construct with specified command_id, command_status, sequence_number and * capacity policy. * * @param commandId is the command_id. * @param commandStatus is the command_status. * @param sequenceNumber is the sequence_number. * @param capacityPolicy is the capacity policy. */ public PDUByteBuffer(int commandId, int commandStatus, int sequenceNumber, CapacityPolicy capacityPolicy) { this(capacityPolicy); append(commandId); append(commandStatus); append(sequenceNumber); normalizeCommandLength(); } /** * Default constructor. */ public PDUByteBuffer() { this(DEFAULT_CAPACITY_POLICY); } /** * Construct with specified capacity policy. * * @param capacityPolicy is the capacity policy. */ public PDUByteBuffer(CapacityPolicy capacityPolicy) { /* * the initial is 4 byte, just for the command_length */ bytes = new byte[4]; this.capacityPolicy = capacityPolicy; bytesLength = 4; normalizeCommandLength(); } /** * Append bytes to specified offset and length. * * @param b is the bytes to append. * @param offset is the offset where the bytes will be placed. * @param length the length that will specified which part of the bytes will * be append. * @return the latest length of the byte buffer. */ public int append(byte[] b, int offset, int length) { int oldLength = bytesLength; bytesLength += length; int newCapacity = capacityPolicy.ensureCapacity(bytesLength, bytes.length); if (newCapacity > bytes.length) { byte[] newB = new byte[newCapacity]; System.arraycopy(bytes, 0, newB, 0, bytes.length); // copy current bytes to new bytes bytes = newB; } System.arraycopy(b, offset, bytes, oldLength, length); // assign value normalizeCommandLength(); return bytesLength; } /** * Append all bytes. * * @param bytes is the bytes to append. * @return the latest length of the buffer. */ public int append(byte[] bytes) { return append(bytes, 0, bytes.length); } /** * Append single byte. * * @param b is the byte to append. * @return the latest length of the buffer. */ public int append(byte b) { return append(new byte[] { b }); } /** * Append int value (contains 4 octet). * * @param intValue is the value to append. * @return the latest length of the buffer. */ public int append(int intValue) { return append(OctetUtil.intToBytes(intValue)); } /** * Append String value. * * @param stringValue * @param nullTerminated true means C-Octet String. * The default value is true. * @return the latest length of the buffer. */ public int append(String stringValue, boolean nullTerminated) { if (stringValue != null) append(stringValue.getBytes()); if (nullTerminated) append((byte)0); return bytesLength; } /** * Append C-Octet String / null terminated String value. * * @param stringValue is the value to append. * @return the latest length of the buffer. */ public int append(String stringValue) { return append(stringValue, true); } /** * Append an optional parameter. * * @param optionalParameter is the optional parameter. * @return the latest length of the buffer. */ public int append(OptionalParameter optionalParameter) { return append(optionalParameter.serialize()); } /** * Append all optional parameters. * * @param optionalParameters is the optional parameters. * @return the latest length of the buffer. */ public int appendAll(OptionalParameter[] optionalParameters) { int length = 0; for (OptionalParameter optionalParamameter : optionalParameters) { length += append(optionalParamameter); } return length; } /** * Assign the proper command length to the first 4 octet. */ private void normalizeCommandLength() { System.arraycopy(OctetUtil.intToBytes(bytesLength), 0, bytes, 0, 4); } /** * Get the composed bytes of PDU. * * @return the composed bytes. */ public byte[] toBytes() { byte[] returnBytes = new byte[bytesLength]; System.arraycopy(bytes, 0, returnBytes, 0, bytesLength); return returnBytes; } int getCommandLengthValue() { return OctetUtil.bytesToInt(bytes, 0); } int getBytesLength() { return bytesLength; } }jsmpp-2.1.2/src/main/java/org/jsmpp/util/PDUComposer.java000066400000000000000000000173231246113105100232010ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import org.jsmpp.InvalidNumberOfDestinationsException; import org.jsmpp.PDUStringException; import org.jsmpp.bean.DestinationAddress; import org.jsmpp.bean.OptionalParameter; import org.jsmpp.bean.UnsuccessDelivery; /** * This is utility to compose the PDU from parameter values to byte. * * @author uudashr * */ public interface PDUComposer { byte[] composeHeader(int commandId, int commandStatus, int sequenceNumber); // GENERAL BIND OPERATION byte[] bind(int commandId, int sequenceNumber, String systemId, String password, String systemType, byte interfaceVersion, byte addrTon, byte addrNpi, String addressRange) throws PDUStringException; byte[] bindResp(int commandId, int sequenceNumber, String systemId, OptionalParameter... optionalParameters) throws PDUStringException; byte[] bindResp(int commandId, int sequenceNumber, String systemId, byte scInterfaceVersion) throws PDUStringException; byte[] unbind(int sequenceNumber); byte[] unbindResp(int commandStatus, int sequenceNumber); byte[] outbind(int sequenceNumber, String systemId, String password) throws PDUStringException; // ENQUIRE_LINK OPERATION byte[] enquireLink(int sequenceNumber); byte[] enquireLinkResp(int sequenceNumber); // GENEICK_NACK OPERATION byte[] genericNack(int commandStatus, int sequenceNumber); // SUBMIT_SM OPERATION /** * Submit short message (submit_sm). * * @param sequenceNumber * @param serviceType * @param sourceAddrTon * @param sourceAddrNpi * @param sourceAddr * @param destAddrTon * @param destAddrNpi * @param destinationAddr * @param esmClass * @param protocolId * @param priorityFlag * @param scheduleDeliveryTime * @param validityPeriod * @param registeredDelivery * @param replaceIfPresentFlag * @param dataCoding * @param smDefaultMsgId * @param shortMessage * @param optionalParameters * @return the composed byte values. * @throws PDUStringException */ byte[] submitSm(int sequenceNumber, String serviceType, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte destAddrTon, byte destAddrNpi, String destinationAddr, byte esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, byte registeredDelivery, byte replaceIfPresentFlag, byte dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException; /** * Submit short message response (submit_sm_resp). * * @param sequenceNumber * @param messageId * @return the composed byte values. * @throws PDUStringException */ byte[] submitSmResp(int sequenceNumber, String messageId) throws PDUStringException; // QUERY_SM OPERATION byte[] querySm(int sequenceNumber, String messageId, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr) throws PDUStringException; byte[] querySmResp(int sequenceNumber, String messageId, String finalDate, byte messageState, byte errorCode) throws PDUStringException; // DELIVER_SM OPERATION byte[] deliverSm(int sequenceNumber, String serviceType, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte destAddrTon, byte destAddrNpi, String destinationAddr, byte esmClass, byte protocolId, byte priorityFlag, byte registeredDelivery, byte dataCoding, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException; byte[] deliverSmResp(int sequenceNumber); /** * Compose data short message (data_sm) PDU. * * @param sequenceNumber * @param serviceType * @param sourceAddrTon * @param sourceAddrNpi * @param sourceAddr * @param destAddrTon * @param destAddrNpi * @param destinationAddr * @param esmClass * @param registeredDelivery * @param dataCoding * @param optionalParameters * @return * @throws PDUStringException */ byte[] dataSm(int sequenceNumber, String serviceType, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte destAddrTon, byte destAddrNpi, String destinationAddr, byte esmClass, byte registeredDelivery, byte dataCoding, OptionalParameter... optionalParameters) throws PDUStringException; /** * Compose data short message response (submit_sm_resp) PDU. * * @param sequenceNumber is the sequence number. * @param messageId is the the message identifier. * @param optionalParameters is the optional parameter(s). * @return the composed byte values. * @throws PDUStringException */ byte[] dataSmResp(int sequenceNumber, String messageId, OptionalParameter... optionalParameters) throws PDUStringException; /** * Compose cancel short message (cancel_sm) PDU. * * @param sequenceNumber * @param serviceType * @param messageId * @param sourceAddrTon * @param sourceAddrNpi * @param sourceAddr * @param destAddrTon * @param destAddrNpi * @param destinationAddr * @return the composed byte values. * @throws PDUStringException */ byte[] cancelSm(int sequenceNumber, String serviceType, String messageId, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte destAddrTon, byte destAddrNpi, String destinationAddr) throws PDUStringException; /** * Compose cancel short message response (cancel_sm_resp) PDU. * * @param sequenceNumber * @return the composed byte values. */ byte[] cancelSmResp(int sequenceNumber); byte[] replaceSm(int sequenceNumber, String messageId, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, String scheduleDeliveryTime, String validityPeriod, byte registeredDelivery, byte smDefaultMsgId, byte[] shortMessage) throws PDUStringException; byte[] replaceSmResp(int sequenceNumber); byte[] submitMulti(int sequenceNumber, String serviceType, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, DestinationAddress[] destinationAddresses, byte esmClass, byte protocolId, byte priorityFlag, String scheduleDeliveryTime, String validityPeriod, byte registeredDelivery, byte replaceIfPresentFlag, byte dataCoding, byte smDefaultMsgId, byte[] shortMessage, OptionalParameter... optionalParameters) throws PDUStringException, InvalidNumberOfDestinationsException; byte[] submitMultiResp(int sequenceNumber, String messageId, UnsuccessDelivery... unsuccessDeliveries) throws PDUStringException; byte[] alertNotification(int sequenceNumber, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte esmeAddrTon, byte esmeAddrNpi, String esmeAddr, OptionalParameter... optionalParameters) throws PDUStringException; }jsmpp-2.1.2/src/main/java/org/jsmpp/util/PDUDecomposer.java000066400000000000000000000202421246113105100235040ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import org.jsmpp.InvalidNumberOfDestinationsException; import org.jsmpp.PDUStringException; import org.jsmpp.bean.AlertNotification; import org.jsmpp.bean.Bind; import org.jsmpp.bean.BindResp; import org.jsmpp.bean.CancelSm; import org.jsmpp.bean.CancelSmResp; import org.jsmpp.bean.Command; import org.jsmpp.bean.DataSm; import org.jsmpp.bean.DataSmResp; import org.jsmpp.bean.DeliverSm; import org.jsmpp.bean.DeliverSmResp; import org.jsmpp.bean.DeliveryReceipt; import org.jsmpp.bean.EnquireLink; import org.jsmpp.bean.EnquireLinkResp; import org.jsmpp.bean.GenericNack; import org.jsmpp.bean.Outbind; import org.jsmpp.bean.QuerySm; import org.jsmpp.bean.QuerySmResp; import org.jsmpp.bean.ReplaceSm; import org.jsmpp.bean.ReplaceSmResp; import org.jsmpp.bean.SubmitMulti; import org.jsmpp.bean.SubmitMultiResp; import org.jsmpp.bean.SubmitSm; import org.jsmpp.bean.SubmitSmResp; import org.jsmpp.bean.Unbind; import org.jsmpp.bean.UnbindResp; /** * This class is provide interface to decompose SMPP PDU bytes form into SMPP * command object. * * @author uudashr * @version 1.0 * @since 1.0 * */ public interface PDUDecomposer { /** * Decompose the header only SMPP PDU command. * * @param b is the PDU. * @return the header ( {@link Command} ) object. */ Command header(byte[] b); // BIND OPERATION /** * Decompose the SMPP PDU bind command. * * @param b is the PDU. * @return the bind command object. * PDUStringException if there is an invalid constraint of * string parameter found. */ Bind bind(byte[] b) throws PDUStringException; /** * Decompose the SMPP PDU bind response command. * * @param b is the PDU. * @return the bind response command object. * @PDUStringException if there is an invalid constraint of * string parameter found. */ BindResp bindResp(byte[] b) throws PDUStringException; /** * Decompose the SMPP PDU unbind command. * * @param b is the PDU. * @return the unbind command object. */ Unbind unbind(byte[] b); /** * Decompose the SMPP PDU unbind response command. * * @param b is the PDU. * @return the unbind response command object. */ UnbindResp unbindResp(byte[] b); /** * Decompose the SMPP PDU outbind command. * * @param b is the PDU. * @return the outbind command object. * PDUStringException if there is an invalid constraint of * string parameter found. */ Outbind outbind(byte[] b) throws PDUStringException; // ENQUIRE_LINK OPERATION /** * Decompose the SMPP PDU enquire link command. * * @param b is the PDU. * @return the enquire link command object. */ EnquireLink enquireLink(byte[] b); /** * Decompose the SMPP PDU enquire link response command. * * @param b is the PDU. * @return the enquire link response command object. */ EnquireLinkResp enquireLinkResp(byte[] b); // GENERICK_NACK OPERATION /** * Decompose the SMPP PDU generic nack command. * * @param b is the PDU. * @return the generic nack command object. */ GenericNack genericNack(byte[] b); // SUBMIT_SM OPERATION /** * Decompose the SMPP PDU submit short message command. * * @param b is the PDU. * @return the submit short message command object. * PDUStringException if there is an invalid constraint of * string parameter found. */ SubmitSm submitSm(byte[] b) throws PDUStringException; /** * Decompose the SMPP PDU submit short message response command. * * @param b is the PDU. * @return the submit short message response command object. * PDUStringException if there is an invalid constraint of * string parameter found. */ SubmitSmResp submitSmResp(byte[] b) throws PDUStringException; // QUERY_SM OPERATION /** * Decompose the SMPP PDU query short message command. * * @param b is the PDU. * @return the query short message command object. * PDUStringException if there is an invalid constraint of * string parameter found. */ QuerySm querySm(byte[] b) throws PDUStringException; /** * Decompose the SMPP PDU query short message reponse command. * * @param b is the PDU. * @return the query short message response command object. * PDUStringException if there is an invalid constraint of * string parameter found. */ QuerySmResp querySmResp(byte[] b) throws PDUStringException; // DELIVER_SM OPERATION /** * Decompose the SMPP PDU deliver short message command. * * @param b is the PDU. * @return the deliver short message command object. * @throws PDUStringException if there is an invalid constraint of * string parameter found. */ DeliverSm deliverSm(byte[] b) throws PDUStringException; /** * Decompose the SMPP PDU deliver short message response command. * * @param b is the PDU. * @return the deliver short message response command object. */ DeliverSmResp deliverSmResp(byte[] b); /** * Decompose the SMPP PDU delivery receipt content. * * @param data is the content. * @return the delivery receipt object. * @throws InvalidDeliveryReceiptException throw if the data is invalid, so * it can be parsed. */ DeliveryReceipt deliveryReceipt(String data) throws InvalidDeliveryReceiptException; /** * Decompose the SMPP PDU delivery receipt content. * * @param data is the content. * @return the delivery receipt object. * @throws InvalidDeliveryReceiptException throw if the data is invalid, so * it can be parsed. */ DeliveryReceipt deliveryReceipt(byte[] data) throws InvalidDeliveryReceiptException; // DATA_SM OPERATION /** * Decompose the SMPP PDU data short message command. * * @param data is the PDU. * @return the data short message command object. * @throws PDUStringException if there is an invalid constraint of * string parameter found. */ DataSm dataSm(byte[] data) throws PDUStringException; /** * Decompose the SMPP PDU data short message response command. * * @param data is the PDU. * @return the data short message command object. * @PDUStringException if there is an invalid constraint of * string parameter found. */ DataSmResp dataSmResp(byte[] data) throws PDUStringException; /** * Decompose the SMPP PDU cancel short message command. * * @param data is the PDU. * @return the cancel short message command object. * @throws PDUStringException if there is an invalid constraint of string * parameter found. */ CancelSm cancelSm(byte[] data) throws PDUStringException; /** * Decompose the SMPP PDU cancel short message response command. * * @param data is the PDU. * @return the cancel short message command object. */ CancelSmResp cancelSmResp(byte[] data); SubmitMulti submitMulti(byte[] data) throws PDUStringException, InvalidNumberOfDestinationsException; SubmitMultiResp submitMultiResp(byte[] data) throws PDUStringException; ReplaceSm replaceSm(byte[] data) throws PDUStringException; ReplaceSmResp replaceSmResp(byte[] data); AlertNotification alertNotification(byte[] data) throws PDUStringException; } jsmpp-2.1.2/src/main/java/org/jsmpp/util/RandomMessageIDGenerator.java000066400000000000000000000032561246113105100256520ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Random; import org.jsmpp.PDUStringException; /** * Generate random alphanumeric * * @author uudashr * @version 1.0 * @since 1.0 * */ public class RandomMessageIDGenerator implements MessageIDGenerator { private Random random; public RandomMessageIDGenerator() { try { random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { random = new Random(); } } /* (non-Javadoc) * @see org.jsmpp.util.MessageIDGenerator#newMessageId() */ public MessageId newMessageId() { /* * use database sequence convert into hex representation or if not using * database using random */ try { synchronized (random) { return new MessageId(Integer.toString(random.nextInt(Integer.MAX_VALUE), 16)); } } catch (PDUStringException e) { throw new RuntimeException("Failed creating message id", e); } } }jsmpp-2.1.2/src/main/java/org/jsmpp/util/RandomSessionIDGenerator.java000066400000000000000000000017721246113105100257120ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import java.util.Random; /** * Session id generator. * * @author uudashr * @version 1.0 * @since 1.0 * */ public class RandomSessionIDGenerator implements SessionIDGenerator { private final Random random = new Random(); /** * Generate new session id. Max 64 char. */ public String newSessionId() { byte[] b = new byte[32]; random.nextBytes(b); return HexUtil.conventBytesToHexString(b); } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/RelativeTimeFormatter.java000066400000000000000000000054571246113105100253240ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import java.text.MessageFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Relative time formatter is {@link TimeFormatter} implementation referred to * SMPP Protocol Specification v3.4 point 7.1.1. * * @author uudashr * */ public class RelativeTimeFormatter implements TimeFormatter { private final TimeZone timezone; /** * Time/Date ASCII format for Absolute Time Format is: * * YYMMDDhhmmsstnnp (refer for SMPP Protocol Specification v3.4) */ private static final String DATE_FORMAT = "{0,number,00}{1,number,00}{2,number,00}{3,number,00}{4,number,00}{5,number,00}000R"; /** * Construct with default timezone. */ public RelativeTimeFormatter() { this(TimeZone.getDefault()); } /** * Construct with specified SMSC timezone. * * @param timezone is the SMSC timezone. */ public RelativeTimeFormatter(TimeZone timezone) { this.timezone = timezone; } public String format(Calendar calendar) { if (calendar == null) { return null; } long relativeTime = calendar.getTimeInMillis() - calendar.getTimeZone().getRawOffset() + timezone.getRawOffset(); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(relativeTime); int year = cal.get(Calendar.YEAR) - 2000; int month = cal.get(Calendar.MONTH) + 1; int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); return format(year, month, day, hour, minute, second); } public String format(Date date) { if (date == null) { return null; } Calendar cal = Calendar.getInstance(); cal.setTime(date); return format(cal); } public static final String format(Integer year, Integer month, Integer day, Integer hour, Integer minute, Integer second) { Object[] args = new Object[] {year, month, day, hour, minute, second}; return MessageFormat.format(DATE_FORMAT, args); } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/Sequence.java000066400000000000000000000024031246113105100226020ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * Sequence number that able to rolling. * * @author uudashr * @version 1.0 * @since 2.0 * */ public class Sequence { private int value; /** * @param start is the start/init value of the sequence. */ public Sequence(int start) { value = start; } /** * Return the next value. * * @return the next value. */ public synchronized int nextValue() { int curValue = value++; if (curValue == Integer.MAX_VALUE) { value = 1; } return curValue; } /** * @return the current value. */ public synchronized int currentValue() { return value; } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/SequentialBytesReader.java000066400000000000000000000067701246113105100253110ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * Utility to read value from bytes sequentially. * * @author uudashr * */ class SequentialBytesReader { private byte[] bytes; int cursor; public SequentialBytesReader(byte[] bytes) { this.bytes = bytes; cursor = 0; } public byte readByte() { return bytes[cursor++]; } public int readInt() { int val = OctetUtil.bytesToInt(bytes, cursor); cursor += 4; return val; } public byte[] readBytesUntilNull() { // TODO uudashr: we can do some improvement here int i = cursor; while (bytes[i++] != (byte)0) { } int length = i - 1 - cursor; if (length == 0) { cursor += 1 + length; return null; } byte[] data = new byte[length]; System.arraycopy(bytes, cursor, data, 0, length); cursor += 1 + length; return data; } /** * @return String value. Nullable. */ public String readCString() { // TODO uudashr: we can do some improvement here int i = cursor; while (bytes[i++] != (byte)0) { } int length = i - 1 - cursor; if (length == 0) { cursor += 1 + length; return null; } String val = new String(bytes, cursor, length); cursor += 1 + length; return val; } public byte[] readBytes(int length) { if (length == 0) return null; byte[] data = new byte[length]; System.arraycopy(bytes, cursor, data, 0, length); cursor += length; return data; } public byte[] readBytes(byte length) { return readBytes(length & 0xff); } /** * @param length * @return String value. Nullable. */ public String readString(int length) { if (length == 0) return null; String val = new String(bytes, cursor, length); cursor += length; return val; } public short readShort() { short value = OctetUtil.bytesToShort(bytes, cursor); cursor += 2; return value; } /** * @param length * @return String value. Nullable. */ public String readString(byte length) { /* * if (length == 0) return null; */ /* * you have to convert the signed byte into unsigned byte (in * integer representation) with & operand by 0xff */ return readString(length & 0xff); /* * String val = new String(_bytes, _cursor, length & 0xff); _cursor += * length; return val; */ } public int remainBytesLength() { return bytes.length - cursor; } public boolean hasMoreBytes() { return cursor < (bytes.length - 1); } public void resetCursor() { cursor = 0; } public byte[] getBytes() { return bytes; } }jsmpp-2.1.2/src/main/java/org/jsmpp/util/SessionIDGenerator.java000066400000000000000000000014461246113105100245470ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * The session id generator. * @author uudashr * @version 1.0 * @since 1.0 * * @param session id */ public interface SessionIDGenerator { /** * @return */ S newSessionId(); } jsmpp-2.1.2/src/main/java/org/jsmpp/util/SimpleCapacityPolicy.java000066400000000000000000000026501246113105100251250ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * Simple implementation of {@link CapacityPolicy}. *

* The calculation looks like * * int newCapcity = (currentCapacity * 3) / 2 + 1 * * and it's only apply if currentCapacity is not greater or equals than requiredCapacity. *

* @author uudashr * */ public class SimpleCapacityPolicy implements CapacityPolicy { /* (non-Javadoc) * @see org.jsmpp.util.CapacityPolicy#ensureCapacity(int, int) */ public int ensureCapacity(int requiredCapacity, int currentCapacity) { if (requiredCapacity > currentCapacity) { int newCapacity = (currentCapacity * 3) / 2 + 1; if (newCapacity < requiredCapacity) { newCapacity = requiredCapacity; } return newCapacity; } else { return currentCapacity; } } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/StopWatch.java000066400000000000000000000023061246113105100227500ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * Simple utility class for watching performance of method invocation. * * @author uudashr * */ public class StopWatch { private long startTime; /** * Start the stop watch. * * @return the current time in millisecond. */ public long start() { return startTime = System.currentTimeMillis(); } /** * Done watching the delay and return the delay between start time to * current time. * * @return the delay between start time to current time */ public long done() { return System.currentTimeMillis() - startTime; } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/StrictBufferedInputStream.java000066400000000000000000000032311246113105100261410ustar00rootroot00000000000000package org.jsmpp.util; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; /** * There were some ongoing bugs related to use of DataInputStream in conjunction * with BufferedInputStream. Listed below: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4112757 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4030995 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4401235 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4100022 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4479751 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6192696 * * This class can be used a drop-in replacement for BufferedInputStream and * provides a workaround to the faulty behavior in BufferedInputStream. * * Adapted from the comment by steffen.hauptmann@epost.de at the URL below: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4030995 * * @author Shantanu Kumar (kumar.shantanu@gmail.com) * */ public class StrictBufferedInputStream extends BufferedInputStream { public StrictBufferedInputStream(final InputStream in) { super(in); } public StrictBufferedInputStream(final InputStream in, final int size) { super(in, size); } /** Workaround for an unexpected behavior of 'BufferedInputStream'! */ @Override public int read(final byte[] buffer, final int bufPos, final int length) throws IOException { int i = super.read(buffer, bufPos, length); if ((i == length) || (i == -1)) return i; int j = super.read(buffer, bufPos + i, length - i); if (j == -1) return i; return j + i; } }jsmpp-2.1.2/src/main/java/org/jsmpp/util/StringParameter.java000066400000000000000000000071311246113105100241440ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import org.jsmpp.SMPPConstant; /** * @author uudashr * @version 1.0 * @since 1.0 * */ public enum StringParameter { /** * system_id string parameter. */ SYSTEM_ID(StringType.C_OCTEC_STRING, 0, 16, true, SMPPConstant.STAT_ESME_RINVSYSID), /** * password string parameter. */ PASSWORD(StringType.C_OCTEC_STRING, 0, 9, true, SMPPConstant.STAT_ESME_RINVPASWD), /** * system_type string parameter. */ SYSTEM_TYPE(StringType.C_OCTEC_STRING, 0, 13, true, SMPPConstant.STAT_ESME_RINVSYSTYP), /** * Invalid address range assume should return the error of invalid source address. */ ADDRESS_RANGE(StringType.C_OCTEC_STRING, 0, 41, true, SMPPConstant.STAT_ESME_RINVSRCADR), SERVICE_TYPE(StringType.C_OCTEC_STRING, 0, 6, true, SMPPConstant.STAT_ESME_RINVSERTYP), SOURCE_ADDR(StringType.C_OCTEC_STRING, 0, 21, true, SMPPConstant.STAT_ESME_RINVSRCADR), DESTINATION_ADDR(StringType.C_OCTEC_STRING, 0, 21, true, SMPPConstant.STAT_ESME_RINVSRCADR), SCHEDULE_DELIVERY_TIME(StringType.C_OCTEC_STRING, 0, 17, false, SMPPConstant.STAT_ESME_RINVSCHED), VALIDITY_PERIOD(StringType.C_OCTEC_STRING, 0, 17, false, SMPPConstant.STAT_ESME_RINVEXPIRY), /** * Validator for DL_NAME (Distribution List) */ DL_NAME(StringType.C_OCTEC_STRING, 0, 21, true, SMPPConstant.STAT_ESME_RINVDLNAME), /** * When validating final date is failed, then we should throw error with status * STAT_ESME_RINVDFTMSGID, means that predefined message are not exist. */ FINAL_DATE(StringType.C_OCTEC_STRING, 0, 17, false, SMPPConstant.STAT_ESME_RINVDFTMSGID), SHORT_MESSAGE(StringType.OCTET_STRING, 0, 254, true, SMPPConstant.STAT_ESME_RINVMSGLEN), MESSAGE_ID(StringType.C_OCTEC_STRING, 0, 65, true, SMPPConstant.STAT_ESME_RINVMSGID), DEL_MESSAGE_ID(StringType.C_OCTEC_STRING, 0, 0, true, SMPPConstant.STAT_ESME_RINVMSGID), /** * ESME_ADDR has error code OK because there is not response to alert_notification * (ESME_ADDR only use on alert_notification), so there is no error code to return. */ ESME_ADDR(StringType.C_OCTEC_STRING, 0, 65, true, SMPPConstant.STAT_ESME_ROK); private StringType type; private final int min; private final int max; private final boolean rangeMinAndMax; private final int errCode; /** * @param type * @param min * @param max * @param rangeMinAndMax * @param errCode AKA error code on command_status. */ private StringParameter(StringType type, int min, int max, boolean rangeMinAndMax, int errCode) { this.type = type; this.min = min; this.max = max; this.rangeMinAndMax = rangeMinAndMax; this.errCode = errCode; } /** * @return Returns the max. */ public int getMax() { return max; } /** * @return Returns the min. */ public int getMin() { return min; } /** * @return Returns the rangeMinAndMax. */ public boolean isRangeMinAndMax() { return rangeMinAndMax; } public StringType getType() { return type; } /** * Get the corresponding error code if the rule has broken. * @return */ public int getErrCode() { return errCode; } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/StringType.java000066400000000000000000000015401246113105100231430ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; /** * String type values. * * @author uudashr * @version 1.0 * @since 1.0 * */ public enum StringType { /** * String delimited by null value. */ C_OCTEC_STRING, /** * String that determined by the length. */ OCTET_STRING; } jsmpp-2.1.2/src/main/java/org/jsmpp/util/StringValidator.java000066400000000000000000000122171246113105100241520ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import org.jsmpp.PDUStringException; /** * String validator for the SMPP PDU string types. * * @author uudashr * @version 1.0 * @since 1.0 * */ public final class StringValidator { private StringValidator() { } public static void validateString(String value, StringParameter param) throws PDUStringException { if (param.getType() == StringType.C_OCTEC_STRING) { if (param.isRangeMinAndMax()) { if (!isCOctetStringValid(value, param.getMax())) { throw new PDUStringException("C-Octet String value '" + value + "' cannot more than " + param.getMax() + ". Actual length of string is " + value.length(), param); } } else if (!isCOctetStringNullOrNValValid(value, param.getMax())) { throw new PDUStringException( "C-Octet String value should be 1 or " + param.getMax() + ". The actual length of string is " + value.length(), param); } } else if (param.getType() == StringType.OCTET_STRING && !isOctetStringValid(value, param.getMax())) { throw new PDUStringException("Octet String value '" + value + "' cannot more than " + param.getMax() + ". Actual length of string is " + value.length(), param); } } public static void validateString(byte[] value, StringParameter param) throws PDUStringException { if (param.getType() == StringType.C_OCTEC_STRING) { if (param.isRangeMinAndMax()) { if (!isCOctetStringValid(value, param.getMax())) { throw new PDUStringException("C-Octet String value '" + new String(value) + "' cannot more than " + param.getMax() + ". Actual length of string is " + value.length, param); } } else if (!isCOctetStringNullOrNValValid(value, param.getMax())) { throw new PDUStringException( "C-Octet String value should be 1 or " + param.getMax() + ". The actual length of string is " + value.length, param); } } else if (param.getType() == StringType.OCTET_STRING && !isOctetStringValid(value, param.getMax())) { throw new PDUStringException("Octet String value '" + new String(value) + "' cannot more than " + param.getMax() + ". Actual length of string is " + value.length, param); } } /** * Validate the C-Octet String. * * @param value * @param maxLength * @return */ static boolean isCOctetStringValid(String value, int maxLength) { if (value == null) return true; if (value.length() >= maxLength) return false; return true; } static boolean isCOctetStringValid(byte[] value, int maxLength) { if (value == null) return true; if (value.length >= maxLength) return false; return true; } /** * Validate the C-Octet String * * @param value * @param length * @return */ static boolean isCOctetStringNullOrNValValid(String value, int length) { if (value == null) { return true; } if (value.length() == 0) { return true; } if (value.length() == length - 1) { return true; } return false; } static boolean isCOctetStringNullOrNValValid(byte[] value, int length) { if (value == null) return true; if (value.length == 0) return true; if (value.length != length) return false; return true; } /** * Validate the Octet String * * @param value * @param maxLength * @return */ static boolean isOctetStringValid(String value, int maxLength) { if (value == null) return true; if (value.length() > maxLength) return false; return true; } static boolean isOctetStringValid(byte[] value, int maxLength) { if (value == null) return true; if (value.length > maxLength) return false; return true; } } jsmpp-2.1.2/src/main/java/org/jsmpp/util/TimeFormatter.java000066400000000000000000000025621246113105100236220ustar00rootroot00000000000000/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.util; import java.util.Calendar; import java.util.Date; /** * This provide time formatter functionality from a type to a String * representation of date that can be recognized based on SMPP protocol. * * @author uudashr * */ public interface TimeFormatter { /** * Format the date to {@link String} representation. * * @param calendar is the calendar to format. * @return the formatted date or null if the date is null. */ String format(Calendar calendar); /** * Format the date to {@link String} representation. * * @param date is the date to format. * @return the formatted date or null if the date is null. */ String format(Date date); } jsmpp-2.1.2/stress/000077500000000000000000000000001246113105100141625ustar00rootroot00000000000000jsmpp-2.1.2/stress/client-log4j.properties000066400000000000000000000011361246113105100205740ustar00rootroot00000000000000log4j.rootLogger=INFO, STDOUT log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout # Pattern to output the caller's file name and line number. log4j.appender.STDOUT.layout.ConversionPattern=%d [%t] %-5p %c - %m%n log4j.appender.FILE=org.apache.log4j.RollingFileAppender log4j.appender.FILE.File=stress/logs/client.log log4j.appender.FILE.MaxFileSize=100KB # Keep one backup file log4j.appender.FILE.MaxBackupIndex=20 log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.ConversionPattern=%d [%t] %-5p %c - %m%njsmpp-2.1.2/stress/runClient.bat000066400000000000000000000005361246113105100166210ustar00rootroot00000000000000@echo off SETLOCAL REM Set Application home directory SET APP_HOME=%~dp0.. cd %APP_HOME% SET LIB_DIR=lib\*.jar @FOR %%V IN (%LIB_DIR%) DO call "lcp.bat" %%~fV @FOR %%V IN (*.jar) DO call "lcp.bat" %%~fV SET CLASSPATH=%LOCALCLASSPATH% echo %CLASSPATH% SET LOCALCLASSPATH= "%JAVA_HOME%\bin\java.exe" %* org.jsmpp.examples.StressClient ENDLOCALjsmpp-2.1.2/stress/runClient.sh000066400000000000000000000020161246113105100164600ustar00rootroot00000000000000#!/bin/bash PRG="$0" progname=`basename "$0"` # need this for relative symlinks while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done APP_HOME=`dirname "$PRG"`/.. cd $APP_HOME # add in the dependency .jar files in non-RPM mode (the default) BASE_LIB=lib for i in "${BASE_LIB}"/*.jar do # if the directory is empty, then it will return the input string # this is stupid, so case for it if [ "$i" != "${BASE_LIB}/*.jar" ] ; then if [ -z "$CLASSPATH" ] ; then CLASSPATH=$i else CLASSPATH="$i":"$CLASSPATH" fi fi done for i in *.jar do # if the directory is empty, then it will return the input string # this is stupid, so case for it if [ "$i" != "*.jar" ] ; then if [ -z "$CLASSPATH" ] ; then CLASSPATH=$i else CLASSPATH="$i":"$CLASSPATH" fi fi done export CLASSPATH java ${*} org.jsmpp.examples.StressClient jsmpp-2.1.2/stress/runServer.bat000066400000000000000000000005361246113105100166510ustar00rootroot00000000000000@echo off SETLOCAL REM Set Application home directory SET APP_HOME=%~dp0.. cd %APP_HOME% SET LIB_DIR=lib\*.jar @FOR %%V IN (%LIB_DIR%) DO call "lcp.bat" %%~fV @FOR %%V IN (*.jar) DO call "lcp.bat" %%~fV SET CLASSPATH=%LOCALCLASSPATH% echo %CLASSPATH% SET LOCALCLASSPATH= "%JAVA_HOME%\bin\java.exe" %* org.jsmpp.examples.StressServer ENDLOCALjsmpp-2.1.2/stress/runServer.sh000066400000000000000000000020161246113105100165100ustar00rootroot00000000000000#!/bin/bash PRG="$0" progname=`basename "$0"` # need this for relative symlinks while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done APP_HOME=`dirname "$PRG"`/.. cd $APP_HOME # add in the dependency .jar files in non-RPM mode (the default) BASE_LIB=lib for i in "${BASE_LIB}"/*.jar do # if the directory is empty, then it will return the input string # this is stupid, so case for it if [ "$i" != "${BASE_LIB}/*.jar" ] ; then if [ -z "$CLASSPATH" ] ; then CLASSPATH=$i else CLASSPATH="$i":"$CLASSPATH" fi fi done for i in *.jar do # if the directory is empty, then it will return the input string # this is stupid, so case for it if [ "$i" != "*.jar" ] ; then if [ -z "$CLASSPATH" ] ; then CLASSPATH=$i else CLASSPATH="$i":"$CLASSPATH" fi fi done export CLASSPATH java ${*} org.jsmpp.examples.StressServer jsmpp-2.1.2/stress/server-log4j.properties000066400000000000000000000011361246113105100206240ustar00rootroot00000000000000log4j.rootLogger=INFO, STDOUT log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout # Pattern to output the caller's file name and line number. log4j.appender.STDOUT.layout.ConversionPattern=%d [%t] %-5p %c - %m%n log4j.appender.FILE=org.apache.log4j.RollingFileAppender log4j.appender.FILE.File=stress/logs/server.log log4j.appender.FILE.MaxFileSize=100KB # Keep one backup file log4j.appender.FILE.MaxBackupIndex=20 log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.ConversionPattern=%d [%t] %-5p %c - %m%njsmpp-2.1.2/testng.xml000066400000000000000000000012021246113105100146600ustar00rootroot00000000000000