Advertisement
Guest User

Untitled

a guest
May 12th, 2017
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.49 KB | None | 0 0
  1. package com.yondu.smppmockclient;
  2.  
  3. import static java.lang.invoke.MethodHandles.lookup;
  4.  
  5. import java.io.BufferedReader;
  6. import java.io.FileInputStream;
  7. import java.io.InputStreamReader;
  8. import java.util.ArrayList;
  9. import java.util.Arrays;
  10. import java.util.HashMap;
  11. import java.util.List;
  12. import java.util.Map;
  13. import java.util.Random;
  14. import java.util.concurrent.Executors;
  15. import java.util.concurrent.ScheduledThreadPoolExecutor;
  16. import java.util.concurrent.ThreadFactory;
  17. import java.util.concurrent.ThreadPoolExecutor;
  18. import java.util.concurrent.atomic.AtomicInteger;
  19.  
  20. import org.slf4j.Logger;
  21. import org.slf4j.LoggerFactory;
  22.  
  23. import com.cloudhopper.commons.charset.Charset;
  24.  
  25. /*
  26.  * #%L
  27.  * ch-smpp
  28.  * %%
  29.  * Copyright (C) 2009 - 2015 Cloudhopper by Twitter
  30.  * %%
  31.  * Licensed under the Apache License, Version 2.0 (the "License");
  32.  * you may not use this file except in compliance with the License.
  33.  * You may obtain a copy of the License at
  34.  *
  35.  *      http://www.apache.org/licenses/LICENSE-2.0
  36.  *
  37.  * Unless required by applicable law or agreed to in writing, software
  38.  * distributed under the License is distributed on an "AS IS" BASIS,
  39.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40.  * See the License for the specific language governing permissions and
  41.  * limitations under the License.
  42.  * #L%
  43.  */
  44.  
  45. import com.cloudhopper.commons.charset.CharsetUtil;
  46. import com.cloudhopper.smpp.SmppBindType;
  47. import com.cloudhopper.smpp.SmppConstants;
  48. import com.cloudhopper.smpp.SmppSession;
  49. import com.cloudhopper.smpp.SmppSessionConfiguration;
  50. import com.cloudhopper.smpp.impl.DefaultSmppClient;
  51. import com.cloudhopper.smpp.impl.DefaultSmppSessionHandler;
  52. import com.cloudhopper.smpp.pdu.DeliverSm;
  53. import com.cloudhopper.smpp.pdu.PduRequest;
  54. import com.cloudhopper.smpp.pdu.PduResponse;
  55. import com.cloudhopper.smpp.pdu.SubmitSm;
  56. import com.cloudhopper.smpp.type.Address;
  57. import com.cloudhopper.smpp.type.SmppInvalidArgumentException;
  58. import com.yondu.smpp.custom.charset.ASCIICharset;
  59. import com.yondu.smpp.custom.charset.ISO2022JPCharset;
  60. import com.yondu.smpp.custom.charset.ISO88595Charset;
  61. import com.yondu.smpp.custom.charset.ISO88598Charset;
  62. import com.yondu.smpp.custom.charset.JISX0208Charset;
  63. import com.yondu.smpp.custom.charset.JISX0212Charset;
  64. import com.yondu.smpp.custom.charset.KSC5601Charset;
  65.  
  66. /**
  67.  *
  68.  * @author joelauer (twitter: @jjlauer or
  69.  *         <a href="http://twitter.com/jjlauer" target=window>http://twitter.com
  70.  *         /jjlauer</a>)
  71.  */
  72. public class ClientMain {
  73.     private static final Logger logger = LoggerFactory.getLogger(lookup().lookupClass());
  74.     private final static Random splitMessagesReferenceGenerator = new Random();
  75.  
  76.     private static final List<Byte> DCS_WITH_140B_LIMIT = Arrays.asList(
  77.             SmppConstants.DATA_CODING_UCS2
  78.             );
  79.    
  80.     private static final List<Byte> DCS_WITH_70_CHARACTER_LIMIT = Arrays.asList(
  81.             SmppConstants.DATA_CODING_JIS,
  82.             SmppConstants.DATA_CODING_EXKANJI,
  83.             SmppConstants.DATA_CODING_MUSIC,
  84.             SmppConstants.DATA_CODING_CYRLLIC,
  85.             SmppConstants.DATA_CODING_KSC5601,
  86.             SmppConstants.DATA_CODING_HEBREW
  87.             );
  88.    
  89.     private static final Map<Byte, Charset> CHARSET_MAP;
  90.  
  91.     static {
  92.         CHARSET_MAP = new HashMap<>();
  93.         CHARSET_MAP.put(SmppConstants.DATA_CODING_DEFAULT, CharsetUtil.CHARSET_GSM);
  94.         CHARSET_MAP.put(SmppConstants.DATA_CODING_IA5, new ASCIICharset());
  95.         CHARSET_MAP.put(SmppConstants.DATA_CODING_LATIN1, CharsetUtil.CHARSET_ISO_8859_1);
  96.         CHARSET_MAP.put(SmppConstants.DATA_CODING_UCS2, CharsetUtil.CHARSET_UCS_2);
  97.         CHARSET_MAP.put(SmppConstants.DATA_CODING_JIS, new JISX0208Charset());
  98.         CHARSET_MAP.put(SmppConstants.DATA_CODING_CYRLLIC, new ISO88595Charset());
  99.         CHARSET_MAP.put(SmppConstants.DATA_CODING_HEBREW, new ISO88598Charset());
  100.         CHARSET_MAP.put(SmppConstants.DATA_CODING_MUSIC, new ISO2022JPCharset());
  101.         CHARSET_MAP.put(SmppConstants.DATA_CODING_EXKANJI, new JISX0212Charset());
  102.         CHARSET_MAP.put(SmppConstants.DATA_CODING_KSC5601, new KSC5601Charset());
  103.     }
  104.  
  105.     static public void main(String[] args) throws Exception {
  106.  
  107.         Map<String, String> parameters = getParametersFromConfigFile(args[0]);
  108.  
  109.         String mobileNumbersStr = parameters.get("mobilenumber");
  110.         String[] mobileNumbersArray = mobileNumbersStr.split(",");
  111.  
  112.         String message = parameters.get("message");
  113.  
  114.         int messageCount = Integer.parseInt(parameters.get("messagecount"));
  115.  
  116.         String shortCode = parameters.get("senderid");
  117.         byte dcs = Byte.parseByte(parameters.get("dcs"));
  118.  
  119.         String username = parameters.get("username");
  120.         String password = parameters.get("password");
  121.         String bindType = parameters.get("bindtype");
  122.         int udhReferenceNumberType = Integer.parseInt(parameters.get("udhReferenceNumberType"));
  123.  
  124.         boolean isSSL = Boolean.parseBoolean(parameters.get("isSSL"));
  125.  
  126.         SmppBindType smppBindType = null;
  127.  
  128.         switch (bindType) {
  129.         case "receiver":
  130.             smppBindType = SmppBindType.RECEIVER;
  131.             break;
  132.         case "transmitter":
  133.             smppBindType = SmppBindType.TRANSMITTER;
  134.             break;
  135.         default:
  136.             smppBindType = SmppBindType.TRANSCEIVER;
  137.         }
  138.  
  139.         String smpphost = parameters.get("smpphost");
  140.         int smppport = Integer.parseInt(parameters.get("smppport"));
  141.  
  142.         boolean concatenate = Boolean.parseBoolean(parameters.get("concatenate"));
  143.         int messageLength = DCS_WITH_140B_LIMIT.contains(dcs) ? Integer.parseInt(parameters.get("messagelength")) * 2
  144.                 : Integer.parseInt(parameters.get("messagelength"));
  145.  
  146.         ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
  147.  
  148.         ScheduledThreadPoolExecutor monitorExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1,
  149.                 new ThreadFactory() {
  150.                     private AtomicInteger sequence = new AtomicInteger(0);
  151.  
  152.                     @Override
  153.                     public Thread newThread(Runnable r) {
  154.                         Thread t = new Thread(r);
  155.                         t.setName("SmppClientSessionWindowMonitorPool-" + sequence.getAndIncrement());
  156.                         return t;
  157.                     }
  158.                 });
  159.  
  160.         DefaultSmppClient clientBootstrap = new DefaultSmppClient(executor, 1, monitorExecutor);
  161.  
  162.         DefaultSmppSessionHandler sessionHandler = new ClientSmppSessionHandler();
  163.  
  164.         SmppSessionConfiguration config0 = new SmppSessionConfiguration();
  165.         config0.setWindowSize(100);
  166.         config0.setName("Tester.Session.0");
  167.         config0.setType(smppBindType);
  168.         config0.setHost(smpphost);
  169.         config0.setPort(smppport);
  170.         config0.setConnectTimeout(10000);
  171.  
  172.         config0.setSystemId(username);
  173.         config0.setPassword(password);
  174.  
  175.         config0.getLoggingOptions().setLogBytes(true);
  176.         config0.setRequestExpiryTimeout(30000);
  177.         config0.setWindowMonitorInterval(15000);
  178.         config0.setCountersEnabled(true);
  179.  
  180.         config0.setUseSsl(isSSL);
  181.  
  182.         SmppSession session0 = null;
  183.  
  184.         try {
  185.             // create session a session by having the bootstrap connect a
  186.             // socket, send the bind request, and wait for a bind response
  187.             session0 = clientBootstrap.bind(config0, sessionHandler);
  188.             String text = message;
  189.             Charset charset = CHARSET_MAP.get(dcs);
  190.             byte[] textBytes = CharsetUtil.encode(text, charset);
  191.             for (int i = 0; i < messageCount; i++) {
  192.                 int mobileNumberIndex = i % mobileNumbersArray.length;
  193.                 String mobileNumber = mobileNumbersArray[mobileNumberIndex];
  194.                 List<SubmitSm> submitSm = createSubmitSm(textBytes, mobileNumber, shortCode, dcs, concatenate,
  195.                         messageLength, udhReferenceNumberType);
  196.                 /* session0.submit(submitSm, 30000); */
  197.                 for (SubmitSm submit : submitSm) {
  198.                     session0.submit(submit, 30000);
  199.                 }
  200.             }
  201.         } catch (Exception e) {
  202.             logger.error("Exception sending the transaction!", e);
  203.         }
  204.     }
  205.  
  206.     private static List<SubmitSm> createSubmitSm(byte[] message, String mobileNumber, String shortcode, byte dcs,
  207.             boolean concatenate, int messageLength, int udhReferenceNumberType) throws SmppInvalidArgumentException {
  208.         List<SubmitSm> submitSmList = new ArrayList<>();
  209.         if (concatenate) {
  210.             byte[] referenceNumber = udhReferenceNumberType == 8 ? new byte[2] : new byte[1];
  211.             splitMessagesReferenceGenerator.nextBytes(referenceNumber);
  212.             byte[][] parts = createConcatenatedBinaryShortMessages(message, referenceNumber, messageLength, dcs);
  213.             if (parts == null) {
  214.                 SubmitSm submitSm = createSubmitSm(message, shortcode, mobileNumber, dcs);
  215.                 submitSmList.add(submitSm);
  216.             } else {
  217.                 for (byte[] part : parts) {
  218.                     SubmitSm submitSm = createSubmitSm(part, shortcode, mobileNumber, dcs);
  219.                     submitSm.setEsmClass(SmppConstants.ESM_CLASS_UDHI_MASK);
  220.                     submitSmList.add(submitSm);
  221.                 }
  222.             }
  223.         } else {
  224.             SubmitSm submitSm = createSubmitSm(message, shortcode, mobileNumber, dcs);
  225.             submitSmList.add(submitSm);
  226.         }
  227.         return submitSmList;
  228.     }
  229.  
  230.     /**
  231.      * Could either implement SmppSessionHandler or only override select methods
  232.      * by extending a DefaultSmppSessionHandler.
  233.      */
  234.     public static class ClientSmppSessionHandler extends DefaultSmppSessionHandler {
  235.  
  236.         public ClientSmppSessionHandler() {
  237.             super(logger);
  238.         }
  239.  
  240.         @Override
  241.         public PduResponse firePduRequestReceived(@SuppressWarnings("rawtypes") PduRequest pduRequest) {
  242.             if (pduRequest instanceof DeliverSm) {
  243.  
  244.                 DeliverSm deliverSm = (DeliverSm) pduRequest;
  245.                 String message = CharsetUtil.decode(deliverSm.getShortMessage(), CharsetUtil.CHARSET_GSM);
  246.                 logger.info("DLR: {}", message);
  247.  
  248.             }
  249.             PduResponse response = pduRequest.createResponse();
  250.             return response;
  251.         }
  252.  
  253.     }
  254.  
  255.     public static Map<String, String> getParametersFromConfigFile(String configfile) {
  256.         Map<String, String> parameters = new HashMap<>();
  257.         InputStreamReader isr = null;
  258.         BufferedReader br = null;
  259.         try {
  260.  
  261.             isr = new InputStreamReader(new FileInputStream(configfile), java.nio.charset.Charset.forName("UTF-8"));
  262.  
  263.             br = new BufferedReader(isr);
  264.             String line;
  265.  
  266.             while ((line = br.readLine()) != null) {
  267.                 line = line.trim();
  268.                 String[] array = line.split("=");
  269.                 if (array.length >= 2) {
  270.                     String value = "";
  271.                     for (int i = 1; i < array.length; i++) {
  272.                         value += array[i];
  273.                     }
  274.                     parameters.put(array[0].trim(), value.trim());
  275.                 }
  276.             }
  277.         } catch (Exception e) {
  278.             e.printStackTrace();
  279.         }
  280.         return parameters;
  281.     }
  282.  
  283.     static public byte[][] createConcatenatedBinaryShortMessages(byte[] binaryShortMessage, byte[] referenceNumber,
  284.             int length, int dcs) throws IllegalArgumentException {
  285.  
  286.         if (binaryShortMessage == null) {
  287.             return null;
  288.         }
  289.  
  290.         if (DCS_WITH_70_CHARACTER_LIMIT.contains((byte) dcs)) {
  291.             return createConcatenatedBinaryShortMessagesByCharacter(binaryShortMessage, referenceNumber, length,
  292.                     (byte) dcs);
  293.         }
  294.  
  295.         // if the short message does not need to be concatenated
  296.         if (binaryShortMessage.length <= length) {
  297.             return null;
  298.         }
  299.  
  300.         int messagePartLength = length - (!DCS_WITH_140B_LIMIT.contains(dcs) ? 7 : 6);
  301.         // since the UDH will be 6 bytes, we'll split the data into chunks of
  302.         // 134
  303.         int numParts = (int) (binaryShortMessage.length / messagePartLength)
  304.                 + (binaryShortMessage.length % messagePartLength != 0 ? 1 : 0);
  305.         // logger.debug("numParts=" + numParts);
  306.  
  307.         byte[][] shortMessageParts = new byte[numParts][];
  308.  
  309.         for (int i = 0; i < numParts; i++) {
  310.             // default this part length to max of 134
  311.             int shortMessagePartLength = messagePartLength;
  312.             if ((i + 1) == numParts) {
  313.                 // last part (only need to add remainder)
  314.                 shortMessagePartLength = binaryShortMessage.length - (i * messagePartLength);
  315.             }
  316.  
  317.             // logger.debug("part " + i + " len: " + shortMessagePartLength);
  318.  
  319.             // part will be UDH (6 bytes) + length of part
  320.             int udhLength = referenceNumber.length == 1 ? 6 : 7;
  321.             byte[] shortMessagePart = new byte[udhLength + shortMessagePartLength];
  322.             setUdh(numParts, i + 1, referenceNumber, shortMessagePart);
  323.  
  324.             // copy this part's user data onto the end
  325.             System.arraycopy(binaryShortMessage, (i * messagePartLength), shortMessagePart, udhLength,
  326.                     shortMessagePartLength);
  327.             shortMessageParts[i] = shortMessagePart;
  328.         }
  329.  
  330.         return shortMessageParts;
  331.     }
  332.  
  333.     private static SubmitSm createSubmitSm(byte[] message, String senderId, String mobileNumber, byte dcs)
  334.             throws SmppInvalidArgumentException {
  335.         SubmitSm submit0 = new SubmitSm();
  336.  
  337.         // add delivery receipt
  338.         // submit0.setRegisteredDelivery(SmppConstants.REGISTERED_DELIVERY_SMSC_RECEIPT_REQUESTED);
  339.  
  340.         submit0.setSourceAddress(new Address((byte) 0x03, (byte) 0x00, senderId));
  341.         submit0.setDestAddress(new Address((byte) 0x01, (byte) 0x01, mobileNumber));
  342.         submit0.setShortMessage(message);
  343.         submit0.setDataCoding(dcs);
  344.  
  345.         return submit0;
  346.     }
  347.  
  348.     static public byte[][] createConcatenatedBinaryShortMessagesByCharacter(byte[] binaryShortMessage,
  349.             byte[] referenceNumber, int length, byte dcs) {
  350.         Charset charset = CHARSET_MAP.get(dcs);
  351.         String message = charset.decode(binaryShortMessage);
  352.         if (message.length() <= length) {
  353.             return null;
  354.         }
  355.         int messagePartLength = length - 3;
  356.         int numParts = (int) (message.length() / messagePartLength)
  357.                 + (message.length() % messagePartLength != 0 ? 1 : 0);
  358.  
  359.         byte[][] shortMessageParts = new byte[numParts][];
  360.         int messagePartStartIndex = 0;
  361.         for (int i = 0; i < numParts; i++) {
  362.             int messagePartEndIndex = (i == numParts - 1) ? message.length()
  363.                     : ((i * messagePartLength) + messagePartLength);
  364.             String messagePart = message.substring(messagePartStartIndex, messagePartEndIndex);
  365.             byte[] messagePartInByteArray = charset.encode(messagePart);
  366.             int udhLength = referenceNumber.length == 1 ? 6 : 7;
  367.             byte[] shortMessagePart = new byte[udhLength + messagePartInByteArray.length];
  368.             setUdh(numParts, i + 1, referenceNumber, shortMessagePart);
  369.             System.arraycopy(messagePartInByteArray, 0, shortMessagePart, udhLength, messagePartInByteArray.length);
  370.             shortMessageParts[i] = shortMessagePart;
  371.             messagePartStartIndex += messagePartLength;
  372.         }
  373.  
  374.         return shortMessageParts;
  375.     }
  376.  
  377.     private static void setUdh(int numberOfParts, int partNumber, byte[] referenceNumber, byte[] shortMessagePart) {
  378.         // if 8bit reference number
  379.         if (referenceNumber.length == 1) {
  380.             shortMessagePart[0] = (byte) 0x05;
  381.             shortMessagePart[1] = (byte) 0x00;
  382.             shortMessagePart[2] = (byte) 0x03;
  383.             shortMessagePart[3] = referenceNumber[0];
  384.             shortMessagePart[4] = (byte) numberOfParts;
  385.             shortMessagePart[5] = (byte) partNumber;
  386.             // else if 16 bit reference number
  387.         } else if (referenceNumber.length == 2) {
  388.             shortMessagePart[0] = (byte) 0x06;
  389.             shortMessagePart[1] = (byte) 0x08;
  390.             shortMessagePart[2] = (byte) 0x04;
  391.             shortMessagePart[3] = referenceNumber[0];
  392.             shortMessagePart[4] = referenceNumber[1];
  393.             shortMessagePart[5] = (byte) numberOfParts;
  394.             shortMessagePart[6] = (byte) partNumber;
  395.         }
  396.     }
  397.  
  398. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement