Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

speed #192

Open
prancius opened this issue Mar 29, 2023 · 1 comment
Open

speed #192

prancius opened this issue Mar 29, 2023 · 1 comment

Comments

@prancius
Copy link

I have problem with sms send speed.
Project working few years and stream increasing so my task find out how to speed up.
Maybe somebody have exemple how to send messages asynchronically?

Thank you a lot

@prancius
Copy link
Author

prancius commented Mar 29, 2023

Is it very bad solution?

package utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.Scanner;
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.BindType;
import org.jsmpp.bean.DataCodings;
import org.jsmpp.bean.DataSm;
import org.jsmpp.bean.DeliverSm;
import org.jsmpp.bean.ESMClass;
import org.jsmpp.bean.MessageType;
import org.jsmpp.bean.NumberingPlanIndicator;
import org.jsmpp.bean.OptionalParameter;
import org.jsmpp.bean.OptionalParameter.Receipted_message_id;
import org.jsmpp.bean.OptionalParameter.Message_state;
import org.jsmpp.bean.OptionalParameter.Tag;
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.TimeFormatter;

public class AsyncDelivery
{
private static TimeFormatter timeFormatter = new AbsoluteTimeFormatter();

final AtomicInteger counter = new AtomicInteger();

private SMPPSession session = null;

private String operator;
private String remoteIpAddress;
private Integer remotePort;
private String user;
private String password;
private BindParameter bindParam;

//Database query size
private int size;

//Sleep after each segment
private int segmentSleep=100;

//Sleep in loop
private int loopSleep=100;

//Operator thread
private int executorId;

//Prefix for response id to unique message id between operators
private String responsePrefix;

public AsyncDelivery(String configFileName)  
{
	
	
	if (this.setConfigValues(configFileName)==true)
	{
			this.bindParam = new BindParameter(BindType.BIND_TRX, this.user, this.password, "cp",TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN, null);
			
			try
			{
				this.session = new SMPPSession(this.remoteIpAddress, this.remotePort, this.bindParam);
			}
			catch(Exception e)
			{
				System.out.println("Can't create session.");
				System.exit(0);
			}
		
	        this.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);
	                    	
	                    	OptionalParameter.Receipted_message_id parameterId = (Receipted_message_id) deliverSm.getOptionalParameter(Tag.RECEIPTED_MESSAGE_ID);
	                    	OptionalParameter.Message_state parameterState = (Message_state) deliverSm.getOptionalParameter(Tag.MESSAGE_STATE);
	                    	
	                    	System.out.println("messageId: " + parameterId.getValueAsString());
	                    	System.out.println("messageState: " + parameterState.getMessageState().name());
	                    	
	                    } 
	                    catch (Exception e) 
	                    {
	                        System.err.println("Failed getting delivery receipt");
	                        e.printStackTrace();
	                    }
	                } 
	                else 
	                {
	                    // regular short message
	                    System.out.println("Receiving message : " + new String(deliverSm.getShortMessage()));
	                }
	            }
	            
	            public void onAcceptAlertNotification(AlertNotification alertNotification) 
	            {
	            }
	            
	            public DataSmResult onAcceptDataSm(DataSm dataSm, Session source)
	                    throws ProcessRequestException 
	            {
	                // TODO Auto-generated method stub
	                return null;
	            }
	        });
		
		
		
	}
	else
	{
		System.out.println("Nepavyko nustatyti parametrų iš config.txt failo!");
		System.exit(0);
	}
}


public static void main(String[] args) 
{
    //Log activation
    //BasicConfigurator.configure();
	
	final AsyncDelivery main = new AsyncDelivery("config_bite.txt");
	
    // Now we will send 50 message asynchronously with max outstanding messages 10.
    ExecutorService execService = Executors.newFixedThreadPool(6);
    
    // requesting delivery report
    final RegisteredDelivery registeredDelivery = new RegisteredDelivery();
    registeredDelivery.setSMSCDeliveryReceipt(SMSCDeliveryReceipt.SUCCESS_FAILURE);
    
    final int maxMessage = 10;
    
    for (int i = 0; i < maxMessage; i++) 
    {
        
        execService.execute(new Runnable() 
        {
            public void run() 
            {
                try 
                {
                    String messageId = main.session.submitShortMessage("CMT", TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN, "NKC", TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN, "37067425942", new ESMClass(), (byte)0, (byte)1,  timeFormatter.format(new Date()), null, registeredDelivery, (byte)0, DataCodings.ZERO, (byte)0, ("jSMPP "+new Date().getTime()).getBytes());
                    System.out.println("Message submitted, message_id is " + messageId);
                } 
                catch (PDUException e) 
                {
                    System.err.println("Invalid PDU parameter");
                    e.printStackTrace();
                    main.counter.incrementAndGet();
                } 
                catch (ResponseTimeoutException e) 
                {
                    System.err.println("Response timeout");
                    e.printStackTrace();
                    main.counter.incrementAndGet();
                } 
                catch (InvalidResponseException e) 
                {
                    // Invalid response
                    System.err.println("Receive invalid respose");
                    e.printStackTrace();
                    main.counter.incrementAndGet();
                } 
                catch (NegativeResponseException e) 
                {
                    // Receiving negative response (non-zero command_status)
                    System.err.println("Receive negative response");
                    e.printStackTrace();
                    main.counter.incrementAndGet();
                } 
                catch (IOException e) 
                {
                    System.err.println("IO error occur");
                    e.printStackTrace();
                    main.counter.incrementAndGet();
                }
            }
        });
    }
    
    while (/*main.counter.get() != maxMessage*/1==1) 
    {
        try { Thread.sleep(100); } catch (InterruptedException e) { }
    }
    
    //main.session.unbindAndClose();
    //execService.shutdown();
    
}


public boolean setConfigValues(String configFileName)
{
	//Skaitom failą config.txt ir nustatymome parametrus
	boolean ret=true;
	
	try 
	{
		
	      File myObj = new File(configFileName);
	      Scanner myReader = new Scanner(myObj);
	    
	      while (myReader.hasNextLine()) 
	      {
	        String line = myReader.nextLine();
	        System.out.println(line);
	        
	        String[] params = line.split(":");
	        
			if (params[0].equals("remoteIpAddress")) 
			{
				this.remoteIpAddress=params[1];
			}
			else if (params[0].equals("remotePort")) 
			{
				this.remotePort = Integer.parseInt(params[1]);
			}
			else if (params[0].equals("user"))
			{
				this.user=params[1];
			}
			else if (params[0].equals("password"))
			{
				this.password=params[1];
			}
			else if (params[0].equals("log_folder"))
			{
				db.PrintLog.logFolder=params[1];
			}
			else if (params[0].equals("operator"))
			{
				this.operator=params[1];
			}
			else if (params[0].equals("size"))
			{
				this.size=Integer.parseInt(params[1]);
			}
			else if (params[0].equals("executor_id"))
			{
				this.executorId=Integer.parseInt(params[1]);
				System.out.println("executorId: " + this.executorId);
			}
			else if (params[0].equals("segment_sleep"))
			{
				this.segmentSleep=Integer.parseInt(params[1]);
				System.out.println("segmentSleep: " + this.segmentSleep);
			}
			else if (params[0].equals("loop_sleep"))
			{
				this.loopSleep=Integer.parseInt(params[1]);
				System.out.println("loopSleep: " + this.loopSleep);
			}
			else if (params[0].equals("response_prefix"))
			{
				this.responsePrefix=params[1];
				System.out.println("response_prefix: " + this.responsePrefix);
			}
			
	      }

	      myReader.close();
	      
	      if (this.remoteIpAddress==null || this.remoteIpAddress.isEmpty()) ret=false;
	      if (this.remotePort==null) ret=false;
	      if (this.user==null || this.user.isEmpty()) ret=false;
	      if (this.password==null || this.password.isEmpty()) ret=false;
	} 
	catch (FileNotFoundException e) 
	{
	     System.out.println(e.toString());
	     ret = false;
	}
	
	return ret;
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant