AWS java/android SDK on SQS: QueueDoesNotExistException - java

I'm trying to delete a message on SQS but with no success. I get a QueueDoesNotExistException even though I just fetched the messages from the url/queue. Can anybody tell me what I'm doing wrong? Here is the function I wrote:
public ArrayList<String> receiveSqsMessages(String url) {
AmazonSQSClient client = getSQSClient(Regions.SA_EAST_1);
ReceiveMessageRequest request = new ReceiveMessageRequest(url);
request.setMaxNumberOfMessages(10);
request.setWaitTimeSeconds(5);
ArrayList<Message> messageList = null;
try {
ReceiveMessageResult result = client.receiveMessage(request);
messageList = new ArrayList<Message>(result.getMessages());
} catch (AmazonClientException ac) {
return null;
}
ArrayList<String> messages = new ArrayList<String>();
for (Message m : messageList) {
String current_message = m.getBody();
if(md5(current_message).equals(m.getMD5OfBody())) {
messages.add(current_message);
String ticket = m.getReceiptHandle();
DeleteMessageRequest delete = new DeleteMessageRequest();
delete.setReceiptHandle(ticket);
client.deleteMessage(delete);
}
}
return messages;
}
private AmazonSQSClient getSQSClient(Regions regions) {
AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY_ID, SECRET_KEY);
Region region = Region.getRegion(regions);
AmazonSQSClient client = new AmazonSQSClient(credentials);
client.setRegion(region);
return client;
}
I confirmed the messages are being retrieved using Log.d in the lines.

You are not setting queueUrl to DeleteMessageRequest. You should call setQueueUrl(String queueUrl) on your DeleteMessageRequest object. You can read more about it on DeleteMessageRequest Javadoc.

Related

The user presence return value is unreadable

I am new to java, for several weeks I have been trying to report the status of a person via microsoft graph, I have no error but the returned value is unreadable. I must be missing something to show the status.
It's a Gradle Project in Eclipse
here is my code:
```public class App {
public static void main(String[] args) {
// <LoadSettingsSnippet>
// Load OAuth settings
final Properties oAuthProperties = new Properties();
try {
oAuthProperties.load(App.class.getResourceAsStream("oAuth.properties"));
} catch (IOException e) {
System.out.println("Unable to read OAuth configuration. Make sure you have a properly formatted oAuth.properties file. See README for details.");
return;
}
final String appId = oAuthProperties.getProperty("app.id");
final List<String> appScopes = Arrays
.asList(oAuthProperties.getProperty("app.scopes").split(","));
// </LoadSettingsSnippet>
// Initialize Graph with auth settings
Graph.initializeGraphAuth(appId, appScopes);
final String accessToken = Graph.getUserAccessToken();
// getpresence
Presence teamCollectionPage = Graph.getPresence();
System.out.println("Valeur Presence : " + teamCollectionPage);
Scanner input = new Scanner(System.in);
``
public class Graph {
private static GraphServiceClient<Request> graphClient = null;
private static TokenCredentialAuthProvider authProvider = null;
public static void initializeGraphAuth(String applicationId, List<String> scopes) {
// Create the auth provider
final DeviceCodeCredential credential = new DeviceCodeCredentialBuilder()
.clientId(applicationId)
.challengeConsumer(challenge -> System.out.println(challenge.getMessage()))
.build();
authProvider = new TokenCredentialAuthProvider(scopes, credential);
// Create default logger to only log errors
DefaultLogger logger = new DefaultLogger();
logger.setLoggingLevel(LoggerLevel.ERROR);
// Build a Graph client
graphClient = GraphServiceClient.builder()
.authenticationProvider(authProvider)
.logger(logger)
.buildClient();
}
public static String getUserAccessToken()
{
try {
URL meUrl = new URL("https://graph.microsoft.com/v1.0/me");
return authProvider.getAuthorizationTokenAsync(meUrl).get();
} catch(Exception ex) {
return null;
}
}
public static Presence getPresence() {
if (graphClient == null) throw new NullPointerException(
"Graph client has not been initialized. Call initializeGraphAuth before calling this method");
GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();
Presence presence = graphClient.users("XXXXXXXXXXXXXXXX").presence()
.buildRequest()
.get();
return presence ;
}
}
the message return is "Valeur Presence : com.microsoft.graph.models.Presence#4d411036"
thank you in advance for your help
What you’re seeing is the default value of Object.toString if the method isn’t overridden in the child class (and it isn’t for the Presence model class).
You can access the value explicitly, e.g.:
System.out.println("Valeur Presence : " + teamCollectionPage.availability);

C# code to add soap header wsse:Security, wsse:BinarySecurityToken,ds:Signature, wsse:UsernameToken,wsu:Timestamp

we are able to invoke the web service from SOAP UI tool by adding key store, Outgoing WS-Security Configuration (TimeStamp, UserName & Signature) and namespaces for usertoken, timestamp body and then apply outgoing wss -> apply "TimeStamp_Signed".
But how to do these things in c# code (we are consuming java web service)
Soap Header :
We are used custom binding option to create these soap headers but when we inspect in IClientMessageInspector -> BeforeSendRequest header was not been created.
Sample Code attached here
public static bool AcceptAllCertificatePolicy(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
private static Binding GetCustomBinding()
{
var asbe = new AsymmetricSecurityBindingElement
{
MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12,
InitiatorTokenParameters = new X509SecurityTokenParameters { InclusionMode = SecurityTokenInclusionMode.Never },
RecipientTokenParameters = new X509SecurityTokenParameters { InclusionMode = SecurityTokenInclusionMode.Never },
MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.SignBeforeEncrypt,
SecurityHeaderLayout = SecurityHeaderLayout.Strict,
EnableUnsecuredResponse = true,
IncludeTimestamp = true
};
asbe.SetKeyDerivation(false);
asbe.AllowSerializedSigningTokenOnReply = true;
asbe.DefaultAlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic128Rsa15;
asbe.EndpointSupportingTokenParameters.Signed.Add(new UserNameSecurityTokenParameters());
asbe.EndpointSupportingTokenParameters.Signed.Add(new X509SecurityTokenParameters());
var myBinding = new CustomBinding();
myBinding.Elements.Add(asbe);
myBinding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));
var httpsBindingElement = new HttpsTransportBindingElement
{
RequireClientCertificate = true
};
myBinding.Elements.Add(httpsBindingElement);
return myBinding;
}
private static Client GetCredentialingClient()
{
var customBinding = GetCustomBinding();
var client = new Client
(customBinding,
new EndpointAddress(new Uri(_endpointAddress),
new DnsEndpointIdentity(_dnsEndpointIdentity),
new AddressHeaderCollection()));
client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode =
System.ServiceModel.Security.X509CertificateValidationMode.None;
client.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;
client.Endpoint.Behaviors.Add(new InspectorBehavior());
SetClientCredentialsSecurity(client.ClientCredentials);
Binding binding = client.Endpoint.Binding;
BindingElementCollection elements = binding.CreateBindingElements();
SecurityBindingElement security = elements.Find<SecurityBindingElement>();
if (security != null)
{
X509SecurityTokenParameters tokenParameters = new X509SecurityTokenParameters();
tokenParameters.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
tokenParameters.RequireDerivedKeys = false;
security.EndpointSupportingTokenParameters.SignedEncrypted.Add(tokenParameters);
client.Endpoint.Binding = new CustomBinding(elements.ToArray());
}
return client;
}
private static void SetClientCredentialsSecurity(ClientCredentials clientCredentials)
{
clientCredentials.ServiceCertificate.Authentication.CertificateValidationMode =
System.ServiceModel.Security.X509CertificateValidationMode.None;
clientCredentials.UserName.UserName = _userName;
clientCredentials.UserName.Password = _password;
clientCredentials.ServiceCertificate.DefaultCertificate = new X509Certificate2(_certificatePath, _certificatePassword);
clientCredentials.ClientCertificate.Certificate = new X509Certificate2(_certificatePath,_certificatePassword);
}
static void Main(string[] args)
{
ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertificatePolicy;
using (var client = GetCredentialingClient())
{
client.Open();
try
{
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Console.ReadLine();
}
Please do help us to create these soap header in c# code
Thank You
You could try to add header in your xml under headers node.
<endpoint address="http://ws-wuxipc-5077:4000/calculator" binding="basicHttpBinding"
contract="ServiceInterface.ICalculatorService" name="cal">
<headers>
<Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:Username>
</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">monMonDePasse</wsse:Password>
<wsse:Nonce>sdsdsdlojhfdsdM5Nw==</wsse:Nonce>
<wsu:Created>2019-01-21T6:17:34Z</wsu:Created>
</wsse:UsernameToken>
</Security>
Or you could add header programmatically through OperationContextScope and XmlDocument.
using (ChannelFactory<ICalculatorService> ChannelFactory = new ChannelFactory<ICalculatorService>("cal"))
{
ICalculatorService employeeService = ChannelFactory.CreateChannel();
using (OperationContextScope scope = new OperationContextScope((IContextChannel)employeeService))
{
System.Xml.XmlDocument document = new XmlDocument();
XmlElement element = document.CreateElement("wsse", "UsernameToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
XmlElement newChild = null;
newChild = document.CreateElement("wsse", "Username", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
newChild.InnerText = "finance";
element.AppendChild(newChild);
newChild = document.CreateElement("wsse", "password", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
newChild.SetAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest");
newChild.InnerText = "387";
element.AppendChild(newChild);
MessageHeader messageHeader = MessageHeader.CreateHeader("security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", element, false);
OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader);
employeeService.Add(5, 6);
}
Console.Read();
}

Get a message's ID using Gmail API from a list so it can be used later in automation

I currently have a quick block of code that will sort through the automation's Gmail account to find the latest message, and list its ID. How exactly can I save that ID to a separate string, so it can be used later on to get the message for comparison. Am I missing a specific line of code, or should I rewrite it in some way? Thanks.
Create a list of the messages using a query. It's going to print the ID of each message.
private List<Message> listMessage(Gmail service,
String query) throws IOException {
ListMessagesResponse response = service.users().messages().list("me").setQ(query).execute();
List<Message> messages = new ArrayList<Message>();
while (response.getMessages() != null) {
messages.addAll(response.getMessages());
if (response.getNextPageToken() != null) {
String pageToken = response.getNextPageToken();
response = service.users().messages().list("me").setQ(query)
.setPageToken(pageToken).execute();
} else {
break;
}
}
if(messages.isEmpty()) {
listMessage(service, query);
}
for (Message message : messages) { //This is going to print the ID of each message.
System.out.println(message.toPrettyString());
}
return messages;
}
This is going to find the latest one.
public void listGmailEmail() {
long unixTime = Instant.now().getEpochSecond();
try {
listMessage(service, "after: " + unixTime);
} catch (IOException ignored) { }
}
I figured it out eventually.
Get list of messages
Turn the list into a JSON
Create a method to get the message
Filter the JSON to get the message ID
Apply the message ID to the new method
Get the message
private List<Message> getMessageID(Gmail service,
String query) throws IOException {
ListMessagesResponse response = service.users().messages().list("me").setQ(query).execute();
List<Message> messages = new ArrayList<Message>();
while (response.getMessages() != null) {
messages.addAll(response.getMessages());
if (response.getNextPageToken() != null) {
String pageToken = response.getNextPageToken();
response = service.users().messages().list("me").setQ(query)
.setPageToken(pageToken).execute();
} else {
break;
}
}
if(messages.isEmpty()) {
getMessageID(service, query);
}
messageID = gson.toJson(messages);
return messages;
}
private Message getEmail(Gmail service, String userId, String messageId)
throws IOException {
Message message = service.users().messages().get(userId, messageId).execute();
email = message.toString();
return message;
}
public void getGmailEmail() {
try {
getMessageID(service, "after: " + unixTime);
messageID = messageID.split("\",")[0].substring(8);
getEmail(service,"me", messageID);
System.out.println("Email received");
emailOrThread = email;
} catch (IOException ignored) { }
}

AWS EC2 Instances: Launch Multiple Instance

I want to create ec2 instances when ever the new user arrive. I created a servlet class to do this. When User arrive i check DB that is user new or not if new then create the instance and send back his/her IP. When i send http request to this servlet one by one for users i get the IP correctly. But when i send HTTP Call in parallel (for user1 send request in tab1, for user2 send request in tab2 simultaneously before getting response from user1 HTTP call). When i do this i got error. Sometimes user1 said
"The instance ID 'i-0b79495934c3b5459' does not exist (Service:
AmazonEC2; Status Code: 400; Error Code: InvalidInstanceID.NotFound;
Request ID: e18a9eaa-cb1b-4130-a3ee-bf1b19fa184c) "
And user2 send IP in response. Kindly help me What is the issue and how to resolve this.
This is the Servlet Class which i created.
public class GateKeeperController extends HttpServlet {
private static final long serialVersionUID = 1L;
BasicAWSCredentials awsCreds = new BasicAWSCredentials(credentials);
AmazonEC2Client ec2Client = new AmazonEC2Client(awsCreds);
RunInstancesRequest runInstancesRequest;
RunInstancesResult runInstancesResult;
Reservation reservation;
Instance intstance;
DescribeInstancesRequest describeInstanceRequest;
DescribeInstancesResult describeInstanceResult;
GatekeeperModal gateKeepermodal;
String sourceAMI = null;
String destinationAMI = null;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession s = request.getSession();
String userID = (String) request.getParameter("userID");
Double lattitude = Double.parseDouble((String) request.getParameter("lat"));
Double lonitude = Double.parseDouble((String) request.getParameter("long"));
if (userID != null) {
Pair coordinates = new Pair(lattitude, lonitude);
RegionSelection targetRegion = new RegionSelection();
String regionResult = targetRegion.getRegion(coordinates);
String instanceIP = null;
gateKeepermodal = new GatekeeperModal();
try {
if (gateKeepermodal.checkUserIsNew(userID)) {
instanceIP = startInstance(userID, regionResult);
if (instanceIP != null) {
response.getWriter().write(instanceIP);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
}
}
private String startInstance(String userID, String region) {
String ami_id = new AMI().getAMI_ID(region);
ec2Client.setEndpoint(region);
runInstancesRequest = new RunInstancesRequest();
runInstancesRequest.withImageId(ami_id).withInstanceType("t2.micro").withMinCount(1).withMaxCount(1)
.withKeyName("GateKeeper_User").withSecurityGroups("GateKeeper User");
runInstancesResult = ec2Client.runInstances(runInstancesRequest);
reservation = runInstancesResult.getReservation();
intstance = reservation.getInstances().get(0);
String s1 = intstance.getState().getName();
String s2 = InstanceStateName.Running.name();
while (!s1.toLowerCase().equals(s2.toLowerCase())) {
describeInstanceRequest = new DescribeInstancesRequest();
describeInstanceRequest.withInstanceIds(intstance.getInstanceId());
ec2Client.setEndpoint(region);
describeInstanceResult = ec2Client.describeInstances(describeInstanceRequest);
reservation = describeInstanceResult.getReservations().get(0);
intstance = reservation.getInstances().get(0);
s1 = intstance.getState().getName();
s2 = InstanceStateName.Running.name();
}
GateKeeperUser user = new GateKeeperUser(userID, intstance.getInstanceId(), intstance.getPublicIpAddress(),
region);
Boolean result;
try {
result = gateKeepermodal.createUser(user);
if (result) {
return intstance.getPublicIpAddress();
} else {
return null;
}
} catch (SQLException e) {
}
return null;
}
}
According to the documentation:
"If you successfully run the RunInstances command, and then
immediately run another command using the instance ID that was
provided in the response of RunInstances, it may return an
InvalidInstanceID.NotFound error. This does not mean the instance does
not exist. Some specific commands that may be affected are:
DescribeInstances: To confirm the actual state of the instance, run
this command using an exponential backoff algorithm.
TerminateInstances: To confirm the state of the instance, first run
the DescribeInstances command using an exponential backoff algorithm."

Using SMPP to send sms texts in JAVA

I am trying to send sms using JAVA. After googling, I found out that SMPP protocol is to be used for it and stumbled upon the below source code.
public class SendSMS
{
public static void main(String[] args) throws Exception
{
SendSMS obj = new SendSMS();
SendSMS.sendTextMessage("<mobile number>");
}
private TimeFormatter tF = new AbsoluteTimeFormatter();
/*
* This method is used to send SMS to for the given MSISDN
*/
public void sendTextMessage(String MSISDN)
{
// bind param instance is created with parameters for binding with SMSC
BindParameter bP = new BindParameter(
BindType.BIND_TX,
"<user_name>",
"<pass_word>",
"<SYSTEM_TYPE>",
TypeOfNumber.UNKNOWN,
NumberingPlanIndicator.UNKNOWN,
null);
SMPPSession smppSession = null;
try
{
// smpp session is created using the bindparam and the smsc ip address/port
smppSession = new SMPPSession("<SMSC_IP_ADDRESS>", 7777, bP);
}
catch (IOException e1)
{
e1.printStackTrace();
}
// Sample TextMessage
String message = "This is a Test Message";
GeneralDataCoding dataCoding = new GeneralDataCoding(false, true,
MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT);
ESMClass esmClass = new ESMClass();
try
{
// submitShortMessage(..) method is parametrized with necessary
// elements of SMPP submit_sm PDU to send a short message
// the message length for short message is 140
smppSession.submitShortMessage(
"CMT",
TypeOfNumber.NATIONAL,
NumberingPlanIndicator.ISDN,
"<MSISDN>",
TypeOfNumber.NATIONAL,
NumberingPlanIndicator.ISDN,
MSISDN,
esmClass,
(byte) 0,
(byte) 0,
tF.format(new Date()),
null,
new RegisteredDelivery(SMSCDeliveryReceipt.DEFAULT),
(byte) 0,
dataCoding,
(byte) 0,
message.getBytes());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
But the problem I encounter with the source code is that it requires specific set of parameters like user_name, pass_word, system_type, SMSC IP address etc which I have no clue of. I have only recently known about the SMPP protocol and so am unaware of how to get this code working to fulfil my usecase of sending sms to my mobile. So can someone please help me get this code to work or guide me to a place where i can learn about doing this?
I've been working on SMPP project recently.
The library I used for SMPP protocol is OpenSMPP.
Here is the example of my class for building and sending SMPP data
public class SmppTransport implements Transport {
#Override
public void send(String url, Map<String, String> map) throws IOException {
int smscPort = Integer.parseInt(map.get("port"));
String smscHost = map.get("send_url");
String smscUsername = map.get("username");
String smscPassword = map.get("password");
String recipientPhoneNumber = map.get("phone_num");
String messageText = map.get("text");
try {
SubmitSM request = new SubmitSM();
// request.setSourceAddr(createAddress(senderPhoneNumber)); // you can skip this
request.setDestAddr(createAddress(recipientPhoneNumber));
request.setShortMessage(messageText);
// request.setScheduleDeliveryTime(deliveryTime); // you can skip this
request.setReplaceIfPresentFlag((byte) 0);
request.setEsmClass((byte) 0);
request.setProtocolId((byte) 0);
request.setPriorityFlag((byte) 0);
request.setRegisteredDelivery((byte) 1); // we want delivery reports
request.setDataCoding((byte) 0);
request.setSmDefaultMsgId((byte) 0);
Session session = getSession(smscHost, smscPort, smscUsername, smscPassword);
SubmitSMResp response = session.submit(request);
} catch (Throwable e) {
// error
}
}
private Session getSession(String smscHost, int smscPort, String smscUsername, String smscPassword) throws Exception{
if(sessionMap.containsKey(smscUsername)) {
return sessionMap.get(smscUsername);
}
BindRequest request = new BindTransmitter();
request.setSystemId(smscUsername);
request.setPassword(smscPassword);
// request.setSystemType(systemType);
// request.setAddressRange(addressRange);
request.setInterfaceVersion((byte) 0x34); // SMPP protocol version
TCPIPConnection connection = new TCPIPConnection(smscHost, smscPort);
// connection.setReceiveTimeout(BIND_TIMEOUT);
Session session = new Session(connection);
sessionMap.put(smscUsername, session);
BindResponse response = session.bind(request);
return session;
}
private Address createAddress(String address) throws WrongLengthOfStringException {
Address addressInst = new Address();
addressInst.setTon((byte) 5); // national ton
addressInst.setNpi((byte) 0); // numeric plan indicator
addressInst.setAddress(address, Data.SM_ADDR_LEN);
return addressInst;
}
}
And my operator gave me this parameters for SMPP. There are many configuration options but these are essential
#host = 192.168.10.10 // operator smpp server ip
#port = 12345 // operator smpp server port
#smsc-username = "my_user"
#smsc-password = "my_pass"
#system-type = ""
#source-addr-ton = 5
#source-addr-npi = 0
So if you want to test your code without registering with GSM service provider, you can simulate SMPP server on your computer. SMPPSim is a great project for testing. Download it and run on your computer. It can be configured in multiple ways e.g. request delivery reports from SMPP server, set sms fail ratio and e.t.c. I've tested SMPPSim on linux.
Use following code for single class execution:
public class SmppTransport {
static Map sessionMap=new HashMap<String,String>();
String result=null;
public String send(String url, Map<String, String> map) throws Exception {
int smscPort = Integer.parseInt(map.get("port"));
String smscHost = map.get("send_url");
String smscUsername = map.get("username");
String smscPassword = map.get("password");
String recipientPhoneNumber = map.get("phone_num");
String messageText = map.get("text");
try {
SubmitSM request = new SubmitSM();
// request.setSourceAddr(createAddress(senderPhoneNumber)); // you can skip this
request.setDestAddr(createAddress(recipientPhoneNumber));
request.setShortMessage(messageText);
// request.setScheduleDeliveryTime(deliveryTime); // you can skip this
request.setReplaceIfPresentFlag((byte) 0);
request.setEsmClass((byte) 0);
request.setProtocolId((byte) 0);
request.setPriorityFlag((byte) 0);
request.setRegisteredDelivery((byte) 1); // we want delivery reports
request.setDataCoding((byte) 0);
request.setSmDefaultMsgId((byte) 0);
Session session = getSession(smscHost, smscPort, smscUsername, smscPassword);
SubmitSMResp response = session.submit(request);
result=new String(response.toString());
} catch (Exception e) {
result=StackTraceToString(e);
}
return result;
}
private Session getSession(String smscHost, int smscPort, String smscUsername, String smscPassword) throws Exception{
if(sessionMap.containsKey(smscUsername)) {
return (Session) sessionMap.get(smscUsername);
}
BindRequest request = new BindTransmitter();
request.setSystemId(smscUsername);
request.setPassword(smscPassword);
request.setSystemType("smpp");
// request.setAddressRange(addressRange);
request.setInterfaceVersion((byte) 0x34); // SMPP protocol version
TCPIPConnection connection = new TCPIPConnection(smscHost, smscPort);
// connection.setReceiveTimeout(BIND_TIMEOUT);
Session session = new Session(connection);
sessionMap.put(smscUsername, session.toString());
BindResponse response = session.bind(request);
return session;
}
private Address createAddress(String address) throws WrongLengthOfStringException {
Address addressInst = new Address();
addressInst.setTon((byte) 5); // national ton
addressInst.setNpi((byte) 0); // numeric plan indicator
addressInst.setAddress(address, Data.SM_ADDR_LEN);
return addressInst;
}
public String StackTraceToString(Exception err) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
err.printStackTrace(pw);
return sw.toString();
}
public String sendSMS(String Port, String Host,String SMPPUserName,String SMPPPassword,String Phone_Number,String Message) throws Exception {
String response=null;
sessionMap.put("port",Port);
sessionMap.put("send_url",Host);
sessionMap.put("username",SMPPUserName);
sessionMap.put("password",SMPPPassword);
sessionMap.put("phone_num",Phone_Number);
sessionMap.put("text",Message);
Set set=sessionMap.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
}
SmppTransport test =new SmppTransport();
try {
response=test.send("10.50.**.**", sessionMap);
System.out.println(response);
} catch (Exception e) {
response=StackTraceToString(e);
}
return response;
}
public static void main(String[] args) throws Exception
{
SmppTransport sm=new SmppTransport();
String test=sm.sendSMS("80*6", "10.50.**.**", "f***obi", "x***fQ", "+9187965*****", "Testing1");
System.out.println("Data: "+test);
}}
Use this simulator here,
It acts as a service provide, after build and test your application on it you have to change just config parameters(username, password, ip, port, ...) that provided to you by the service provider .
you can find all configurations to connect to this simulator in conf file.
SMPP is a protocol between mobile network operators/carriers and content providers. The fields you specified (username, password, SMSC IP) are provisioned from the operators. Unfortunately, unless you work for a content provider company, or have a deal with an operator, you are unlikely to get these details.
Simulators can let you test out your SMPP code but they will not actually deliver content to your phone.
My best advice if you want to send SMS from your Java app would be to use an SMS API like Twilio's.

Categories

Resources