AWS EC2 Instances: Launch Multiple Instance - java

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."

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);

BufferingResponseListener and getContentAsString append the previously fetched content

I run a custom WebSocketServlet for Jetty, which sends short text push notifications (for an async mobile and desktop word game) to many platforms (Facebook, Vk.com, Mail.ru, Ok.ru also Firebase and Amazon messaging) using a Jetty HttpClient instance:
public class MyServlet extends WebSocketServlet {
private final SslContextFactory mSslFactory = new SslContextFactory();
private final HttpClient mHttpClient = new HttpClient(mSslFactory);
#Override
public void init() throws ServletException {
super.init();
try {
mHttpClient.start();
} catch (Exception ex) {
throw new ServletException(ex);
}
mFcm = new Fcm(mHttpClient); // Firebase
mAdm = new Adm(mHttpClient); // Amazon
mApns = new Apns(mHttpClient); // Apple
mFacebook = new Facebook(mHttpClient);
mMailru = new Mailru(mHttpClient);
mOk = new Ok(mHttpClient);
mVk = new Vk(mHttpClient);
}
This has worked very good for the past year, but since I have recently upgraded my WAR-file to use Jetty 9.4.14.v20181114 the trouble has begun -
public class Facebook {
private final static String APP_ID = "XXXXX";
private final static String APP_SECRET = "XXXXX";
private final static String MESSAGE_URL = "https://graph.facebook.com/%s/notifications?" +
// the app access token is: "app id | app secret"
"access_token=%s%%7C%s" +
"&template=%s";
private final HttpClient mHttpClient;
public Facebook(HttpClient httpClient) {
mHttpClient = httpClient;
}
private final BufferingResponseListener mMessageListener = new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
if (!result.isSucceeded()) {
LOG.warn("facebook failure: {}", result.getFailure());
return;
}
try {
// THE jsonStr SUDDENLY CONTAINS PREVIOUS CONTENT!
String jsonStr = getContentAsString(StandardCharsets.UTF_8);
LOG.info("facebook success: {}", jsonStr);
} catch (Exception ex) {
LOG.warn("facebook exception: ", ex);
}
}
};
public void postMessage(int uid, String sid, String body) {
String url = String.format(MESSAGE_URL, sid, APP_ID, APP_SECRET, UrlEncoded.encodeString(body));
mHttpClient.POST(url).send(mMessageListener);
}
}
Suddenly the getContentAsString method called for successful HttpClient invocations started to deliver the strings, which were fetched previously - prepended to the the actual result string.
What could it be please, is it some changed BufferingResponseListener behaviour or maybe some non-obvious Java quirk?
BufferingResponseListener was never intended to be reusable across requests.
Just allocate a new BufferingResponseListener for every request/response.

Unrecognized temporary token when attempting to complete authorization: FITBIT4J

I am trying to create a app for fitbit using fitbit4j . I found their sample code
at
https://github.com/apakulov/fitbit4j/blob/master/fitbit4j-example-client/src/main/java/com/fitbit/web/FitbitApiAuthExampleServlet.java
When i tried to implement it I am getting many errors.
below is their doGet function()
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
FitbitAPIClientService<FitbitApiClientAgent> apiClientService = new FitbitAPIClientService<FitbitApiClientAgent>(
new FitbitApiClientAgent(apiBaseUrl, fitbitSiteBaseUrl, credentialsCache),
clientConsumerKey,
clientSecret,
credentialsCache,
entityCache,
subscriptionStore
);
if (request.getParameter("completeAuthorization") != null) {
String tempTokenReceived = request.getParameter(OAUTH_TOKEN);
String tempTokenVerifier = request.getParameter(OAUTH_VERIFIER);
APIResourceCredentials resourceCredentials = apiClientService.getResourceCredentialsByTempToken(tempTokenReceived);
if (resourceCredentials == null) {
throw new ServletException("Unrecognized temporary token when attempting to complete authorization: " + tempTokenReceived);
}
// Get token credentials only if necessary:
if (!resourceCredentials.isAuthorized()) {
// The verifier is required in the request to get token credentials:
resourceCredentials.setTempTokenVerifier(tempTokenVerifier);
try {
// Get token credentials for user:
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
} catch (FitbitAPIException e) {
throw new ServletException("Unable to finish authorization with Fitbit.", e);
}
}
try {
UserInfo userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
request.setAttribute("userInfo", userInfo);
request.getRequestDispatcher("/fitbitApiAuthExample.jsp").forward(request, response);
} catch (FitbitAPIException e) {
throw new ServletException("Exception during getting user info", e);
}
} else {
try {
response.sendRedirect(apiClientService.getResourceOwnerAuthorizationURL(new LocalUserDetail("-"), exampleBaseUrl + "/fitbitApiAuthExample?completeAuthorization="));
} catch (FitbitAPIException e) {
throw new ServletException("Exception during performing authorization", e);
}
}
}
When i run the code it goes into the 'else' part first and i get the URL with
localhost:8080/fitbitApiAuthExample?completeAuthorization=&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX, and i get the fitbit login screen and when i log in
and since the
'completeAuthorization==null',
it is executing the else part again.So i manually added a value so that it will enter the 'if' section .
So the new URL became
localhost:8080/fitbitApiAuthExample?completeAuthorization=Success&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX and entered the 'if' section.
Now am getting the exception
'Unrecognized temporary token when attempting to complete authorization:'I tried many workarounds but still cant understand the error.
Please Help.
Solved the problem. the 'apiClientService' was going null when i reload the servlet. Made it member variable and everything started working.
public class NewServlet extends HttpServlet {
public String apiBaseUrl = "api.fitbit.com";
public String webBaseUrl = "https://www.fitbit.com";
public String consumerKey = "your key";
public String consumerSecret = "your secret";
public String callbackUrl = "*****/run?Controller=Verifier";
public FitbitAPIClientService<FitbitApiClientAgent> apiClientService = null;
public String oauth_token = null;
public String oauth_verifier = null;
public String token = null;
public String tokenSecret = null;
public String userId = null;
public APIResourceCredentials resourceCredentials=null;
public FitbitApiClientAgent agent =null;
public LocalUserDetail user=null;
public Gson gson =null;
public UserInfo userInfo=null;
private static Properties getParameters(String url) {
Properties params = new Properties();
String query_string = url.substring(url.indexOf('?') + 1);
String[] pairs = query_string.split("&");
for (String pair : pairs) {
String[] kv = pair.split("=");
params.setProperty(kv[0], kv[1]);
}
return params;
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ParserConfigurationException, SAXException, Exception {
PrintWriter out = response.getWriter();
response.addHeader("Access-Control-Allow-Origin", "*");
// out.println(" ----- process Request Called-----");
String controllerValue = request.getParameter("Controller");
// out.println(" Controller Request : "+param);
if (controllerValue == null) {
// out.println(" inside if part ");
FitbitAPIEntityCache entityCache = new FitbitApiEntityCacheMapImpl();
FitbitApiCredentialsCache credentialsCache = new FitbitApiCredentialsCacheMapImpl();
FitbitApiSubscriptionStorage subscriptionStore = new FitbitApiSubscriptionStorageInMemoryImpl();
FitbitApiClientAgent apiClientAgent = new FitbitApiClientAgent(apiBaseUrl, webBaseUrl, credentialsCache);
out.println("testing2");
apiClientService
= new FitbitAPIClientService<FitbitApiClientAgent>(
apiClientAgent,
consumerKey,
consumerSecret,
credentialsCache,
entityCache,
subscriptionStore
);
// out.println("<script>localStorage.setItem('api',apiClientService);</script>");
LocalUserDetail userDetail = new LocalUserDetail("-");
try {
// out.println("testing4");
String authorizationURL = apiClientService.getResourceOwnerAuthorizationURL(userDetail, callbackUrl);
out.println("access by web browser: " + authorizationURL);
out.println("Your web browser shows redirected URL.");
out.println("Input the redirected URL and push Enter key.");
response.sendRedirect(authorizationURL);
} catch (FitbitAPIException ex) {
out.println("exception : " + ex);
//Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (controllerValue.equalsIgnoreCase("Verifier")) {
oauth_token = request.getParameter("oauth_token");
oauth_verifier = request.getParameter("oauth_verifier");
resourceCredentials = apiClientService.getResourceCredentialsByTempToken(oauth_token);
if (resourceCredentials == null) {
out.println(" resourceCredentials = null ");
throw new Exception("Unrecognized temporary token when attempting to complete authorization: " + oauth_token);
}
if (!resourceCredentials.isAuthorized()) {
resourceCredentials.setTempTokenVerifier(oauth_verifier);
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
}
userId = resourceCredentials.getLocalUserId();
token = resourceCredentials.getAccessToken();
tokenSecret = resourceCredentials.getAccessTokenSecret();
user = new LocalUserDetail(userId);
userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
user = new LocalUserDetail(userId);
agent = apiClientService.getClient();
response.sendRedirect("http://localhost:8084/FitbitClientCheck/");
}

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.

AWS java/android SDK on SQS: QueueDoesNotExistException

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.

Categories

Resources