Unable to get original string message send from third party system - spring-boot

When getting message from third part system using MQ, it is displaying like bytes array instead of original string sent by third party system.
For example:
Original Json String sent bt third part system {"name":"sonoo","salary":600000.0,"age":27}
Received String from MQ is : 123,34,82,101,103,68,101,99,77,115,103,34,58,123,34,72,100,114,34,58,123,34,64,84,109,79,102,102,34,58,34,43,48,56,58,48,48,34,44,34,64,68,116,109,34,58,34,50,48,50,51,45,48,49,45,49,56
Expected result: {"name":"sonoo","salary":600000.0,"age":27}
#GenerateTransactionID
#JmsListener(destination = "${mq.queueName}", containerFactory = "${mq.containerFactory}", concurrency = "${mq.receiver.concurrency}")
public void receiveMessage(String jsonString) {
try
{
logger.debug(" Message received from third party::: " +jsonString);
if(jsonString.contains("RegDecMsg") && jsonString.contains("DocId")) {
Map<String, Object> jsonMap = dmgJsonParser.parseAsTree(jsonString);
StringBuilder sb = new StringBuilder();
printMapForDebugging(jsonMap, sb, jsonString);
logger.debug(" Attributes \n {}" +sb);
dmgJsonTraverser.processJsonNodes(jsonMap);
} else {
logger.debug(" Received message from third party is not in the expected format::: " +jsonString);
}
} catch (NullPointerException nx) {
logger.error(" Error while processing message:: "+ jsonString, " Please contact support!! ", nx);
} catch (Exception ex) {
logger.error(" Error while processing message:: "+ jsonString, " Please contact support!! ", ex);
throw ex;
}
}

Related

SSE server sending events in a batch on final close

I have a Jersey server running locally, it exposes a SSE resource just like the examples here: https://jersey.github.io/documentation/latest/sse.html. I have a local webpack Angular app, that binds to the exposed GET endpoint and listens for data.
On the GET, I start up a thread to send notifications at regular intervals over 6-8 seconds. I don't see anything on the client UNTIL the EventOutput object is closed.
What am I doing wrong, and how can I fix this?
The server code WORKS with just a simple curl, i.e.:
curl http://localhost:8002/api/v1/notify
But on both Chrome and Safari the following code exhibits the behavior
Client (TypeScript):
this.evSource = new EventSource('http://localhost:8002/api/v1/notify');
this.evSource.addEventListener(
'event',
(x => console.log('we have ', x))
);
this.evSource.onmessage = (data => console.log(data));
this.evSource.onopen = (data => console.log(data));
this.evSource.onerror = (data => {
console.log(data);
this.evSource.close();
});
Server (Java):
// cache callback
public void eventCallback(Iterable<CacheEntryEvent<? extends Integer, ? extends Integer>> events) {
for (CacheEntryEvent<? extends Integer, ? extends Integer> x : events) {
LOGGER.info("{} Sending the following value: " + x.getValue(), Thread.currentThread().getId());
final OutboundEvent sseEvent = new OutboundEvent.Builder().name("event")
.data(Integer.class, x.getValue()).build();
this.broadcaster.broadcast(sseEvent);
}
}
#GET
#Produces(SseFeature.SERVER_SENT_EVENTS)
#ApiOperation(value = "Setup SSE pipeline", notes = "Sets up the notification pipeline for clients to access")
#ApiResponses(value = {
#ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED,
message = "Missing, bad or untrusted cookie"),
#ApiResponse(code = HttpURLConnection.HTTP_OK,
message = "Events streamed successfully")
})
#Timed
#ResponseMetered
public EventOutput registerNotificationEvents(
#HeaderParam(SseFeature.LAST_EVENT_ID_HEADER) String lastEventId,
#QueryParam(SseFeature.LAST_EVENT_ID_HEADER) String lastEventIdQuery) {
if (!Strings.isNullOrEmpty(lastEventId) || !Strings.isNullOrEmpty(lastEventIdQuery)) {
LOGGER.info("Found Last-Event-ID header: {}", !Strings.isNullOrEmpty(lastEventId) ? lastEventId : lastEventIdQuery );
}
LOGGER.info("{} Received request", Thread.currentThread().getId());
this.continuation = true;
final EventOutput output = new EventOutput();
broadcaster.add(output);
Random rand = new Random();
IntStream rndStream = IntStream.generate(() -> rand.nextInt(90));
List<Integer> lottery = rndStream.limit(15).boxed().collect(Collectors.toList());
IgniteCache<Integer, Integer> cache = this.ignite.cache(topic_name);
executorService.execute(() -> {
try {
lottery.forEach(value -> {
try {
TimeUnit.MILLISECONDS.sleep(500);
LOGGER.info("{} Sending the following value to Ignite: " + value + " : " + count++, Thread.currentThread().getId());
if (!cache.isClosed()) {
cache.put(1, value);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
});
TimeUnit.MILLISECONDS.sleep(500);
continuation = false;
TimeUnit.MILLISECONDS.sleep(500);
if (!output.isClosed()) {
// THIS is where the client sees ALL the data broadcast
// in one shot
output.close();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
});
LOGGER.info("{} Completing request", Thread.currentThread().getId());
return output;
}
}
Looks like http://github.com/dropwizard/dropwizard/issues/1673 captures the problem. GZip default won't flush even if upper levels ask for it. Solution is something like
((AbstractServerFactory)configuration.getServerFactory()).getGzipFilterFactory().setSyncFlush(true);
will enable flushing to synchronize with GZip if disabling GZip all up is not an option

MQQueue get call fails to get the message from queue

MQQueue get call fails to retrieve the message from the queue with 2033 (07F1) (RC2033): MQRC_NO_MSG_AVAILABLE error. I am using the following code to get the message from the queue:
GET message:
byte[] replyMessageBytes = null;
try {
this.replyConnection.open();
MQQueue replyQueue = this.replyConnection.getQueue(CMQC.MQOO_INPUT_AS_Q_DEF);
if (null == replyQueue) {
logger.error("Could not create reply queue.");
throw new PFMCommunicationException("Could not create reply queue.");
}
MQMessage replyMessage = new MQMessage();
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.resolvedQueueName = replyQueue.getResolvedQName();
if (timeout.length > 0) {
try {
gmo.waitInterval = Integer.valueOf("" + timeout[0]);
} catch (NumberFormatException e) {
}
} else {
gmo.waitInterval = MQConstants.MQWI_UNLIMITED;
}
gmo.options = MQConstants.MQGMO_WAIT;
if (null != correlationId) {
gmo.matchOptions = MQConstants.MQMO_MATCH_MSG_ID | MQConstants.MQMO_MATCH_CORREL_ID;
replyMessage.messageId = correlationId.getBytes();
replyMessage.correlationId = correlationId.getBytes();
} else {
gmo.matchOptions = MQConstants.MQMO_NONE;
replyMessage.messageId = MQConstants.MQMI_NONE;
replyMessage.correlationId = MQConstants.MQCI_NONE;
}
try {
replyQueue.get(replyMessage, gmo);
int length = replyMessage.getMessageLength();
replyMessageBytes = replyMessage.readStringOfByteLength(length).getBytes();
} catch (MQException e) {
logger.error("ERROR on receiving reply: CC=" + e.completionCode + " RC=" + e.reasonCode + " "
+ e.getMessage());
} catch (IOException e) {
logger.error("ERROR on receiving reply.", e);
}
if (null == replyMessageBytes) {
logger.error("No reply received.");
} else {
logger.debug("Received message: " + new String(replyMessageBytes));
}
} catch (MQException e) {
logger.error("ERROR:", e);
throw new PFMCommunicationException(e);
} catch (PFMConnectionException e) {
logger.error(e.getMessage());
throw new PFMCommunicationException(e);
} finally {
this.replyConnection.close();
logger.debug("Closed connection with MQ replies.");
}
I confirm that the message is present in the queue before the waitInterval expires and the correlationId also matches. In-fact, when I run the code without trying to match the correlationId, I am able to get the message. I guess this means either something is wrong with the response message or I am making a mistake creating the matchOptions properly.
gmo.matchOptions = MQConstants.MQMO_NONE;
replyMessage.messageId = MQConstants.MQMI_NONE;
replyMessage.correlationId = MQConstants.MQCI_NONE;
This is what my response message header looks like:
<Header Origin="DISPUTE1" Addressee="PSXDX2" Date="20180802" Time="123055" Area="QUERY" Content="RAddr" ID="8af3257cf01a4842bf5eec8d" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="cms/customerAccountDetails.xsd">
I tried with putting CorrelId instead of ID in the response header but it's still the same. Can someone please help me to find the issue?
if (null != correlationId) {
gmo.matchOptions = MQConstants.MQMO_MATCH_MSG_ID | MQConstants.MQMO_MATCH_CORREL_ID;
replyMessage.messageId = correlationId.getBytes();
replyMessage.correlationId = correlationId.getBytes();
}
Well, that's your problem. It would be extremely rare, if ever, that an MQ message would have the same value in BOTH the MsgId and CorrelId fields.
If you are getting a reply message for a request that you sent, and you saved the request message's MsgId after the MQPUT, then the code should be:
if (null != correlationId) {
gmo.matchOptions = MQConstants.MQMO_MATCH_CORREL_ID;
replyMessage.correlationId = correlationId.getBytes();
}
Note: You don't save the request (outbound) message's CorrelId but rather the MsgId. The server processing your request, should put the incoming MsgId in the reply message's CorrelId. Hence, that is why you ONLY match on CorrelId for the reply message.

Sms not receiving from java web application

I have written java code which is used to send sms using sms gateway. JAVA OpenSMPP API is used to implement the logic for sending SMPP request. I have needed below information which is used to connect to the sms gateway and which is used to send sms :
SMS_GATEWAY_USERNAME 906o2portt02
SMS_GATEWAY_PORT 9205 S
SMS_GATEWAY_IP_2 34.22.91.166
SMS_GATEWAY_IP_1 80.77.67.145
I am able to send sms but i dont understand for what reason i am not receiving sms. I have also put the debug statement in my code to check for any error. When i checked the log file i am getting below information which says sms has been send. Previously I had different port number,username and password and i was able to send and recieve sms using the same java code. But now i have the requirement to send sms on this gateway and its also sending an sms. but for some reason i am not receiving sms. Is there any way to check what happened to my sms which has been send ?
Below is my code :
public class SMSClient
{
private static final Logger logger = LoggerFactory
.getLogger(SMSClient.class);
#Autowired
private SMSSettings smsSettings;
#Autowired
private OracleSettings oracleSettings;
/**
* If the application is bound to the SMSC.
*/
boolean _bound = false;
public boolean send(String text,
List<AlertCommunicationAddress> toAddressesSMS)
{
List<String> toAddressesSMSString = new ArrayList<String>();
for (AlertCommunicationAddress alertComAddr : toAddressesSMS)
{
List<AlertRecpGrpMember> recpMembers = alertComAddr
.getAlertRecipientsGroup().getAlertRecpGrpMembers();
for (AlertRecpGrpMember recpMem : recpMembers)
{
// check here if the member belongs to the same environment on
// which SMS is being sent.
if ((recpMem.getIsDefault() != null && recpMem.getIsDefault()
.equalsIgnoreCase("Y"))
|| (recpMem.getRunEnvironment() != null && recpMem
.getRunEnvironment().equalsIgnoreCase(
oracleSettings.getRunEnv())))
{
toAddressesSMSString.add(recpMem.getMember());
}
}
}
logger.debug("Original SMS to be sent : " + text);
String smscHost1 = smsSettings.getHost1();
Integer smscPort = smsSettings.getPort();
if (toAddressesSMSString.isEmpty())
{
return false;
}
for (String phoneNumber : toAddressesSMSString)
{
try
{
Session session = getSession(smscHost1, smscPort,
smsSettings.getUsername(), smsSettings.getPassword());
if (session == null)
{
String smscHost2 = smsSettings.getHost2();
logger.error("SMS --- Unable to get the session with Host 1 (" + smscHost1 + ":" + smscPort + ") , will try Host 2 (" + smscHost2 + ") now.");
session = getSession(smscHost2, smscPort,
smsSettings.getUsername(),
smsSettings.getPassword());
if (session == null)
{
logger.error("SMS --- Unable to get the session with Host 1 (" + smscHost1 + ") and Host 2 (" + smscHost2 + "). Please check with the SMS Gateway.");
return false;
}
}
logger.debug("SMS --- Created Session object " + session);
SubmitSM request = new SubmitSM();
request.setSourceAddr(new Address((byte) 5, (byte) 0,
"RM2Support"));
request.setDestAddr(createAddress(phoneNumber));
request.setProtocolId((byte) 0);
request.setPriorityFlag((byte) 0);
request.setRegisteredDelivery((byte) 1); // we want delivery
// reports
request.setDataCoding((byte) 0);
request.setSmDefaultMsgId((byte) 0);
// request.setScheduleDeliveryTime(deliveryTime); // you can
// skip
// this
request.setReplaceIfPresentFlag((byte) 0);
// Send the request
request.assignSequenceNumber(true);
// this is to send long messages
request.setEsmClass((byte) Data.SM_UDH_GSM);
String[] splittedMsg = splitMessage(text, 153);
int totalSegments = splittedMsg.length;
logger.debug("SMS : Number of splitted segments :: "
+ totalSegments);
// iterating on splittedMsg array. Only Sequence Number and
// short
// message text will change each time
Random random = new Random();
int randomInt = random.nextInt();
logger.debug("SMS---- Reference Number : " + randomInt);
for (int i = 0; i < totalSegments; i++)
{
ByteBuffer ed = new ByteBuffer();
ed.appendByte((byte) 5); // UDH Length
ed.appendByte((byte) 0x00); // IE Identifier
ed.appendByte((byte) 3); // IE Data Length
ed.appendByte((byte) randomInt); // Reference Number
ed.appendByte((byte) totalSegments); // Number of pieces
ed.appendByte((byte) (i + 1)); // Sequence number
ed.appendString(splittedMsg[i], Data.ENC_ASCII);
request.setShortMessageData(ed);
logger.debug("Hello...reached here...now about the submit the request::::");
SubmitSMResp response = session.submit(request);
logger.debug("SMS --- Submit response "
+ response.getCommandStatus());
// response = smsSession.submitMulti(request);
logger.debug("SMS --- Submit response "
+ response.getCommandStatus());
String messageId = response.getMessageId();
logger.debug("SMS --- Message ID = " + messageId);
}
enquireLink(session);
unbind(session);
} catch (Exception e)
{
logger.debug("Exception while sending SMS with Phone number :::" + phoneNumber + "::::" + e);
continue;
}
}
return true;
}
private Session getSession(String smscHost, int smscPort,
String smscUsername, String smscPassword) throws Exception
{
try
{
TCPIPConnection connection = new TCPIPConnection(smscHost, smscPort);
connection.setReceiveTimeout(6000);
connection.setIOBufferSize(8188);
connection.setReceiveBufferSize(8188);
Session session = new Session(connection);
// bind now
if (_bound)
{
logger.debug("Already bound, unbind first.");
return session;
}
BindRequest request = new BindTransmitter();
request.setSystemId(smscUsername);
request.setPassword(smscPassword);
// request.setSystemType(systemType);
// request.setAddressRange(addressRange);
request.setInterfaceVersion((byte) 0x34); // SMPP protocol version
logger.debug("SMS --- Bind request :: " + request.debugString());
logger.debug("SMS --- Created Session object :: " + session);
BindResponse response = session.bind(request);
logger.debug("Bind response " + response.debugString());
if (response.getCommandStatus() == Data.ESME_ROK)
{
logger.debug("SMS --- Binded with SMSC Server");
_bound = true;
} else
{
logger.error("SMS --- Unable to bind with SMSC Server :: Code :: "
+ response.getCommandStatus());
}
Integer respCode = new Integer(response.getCommandStatus());
logger.debug("SMS -- Response Code ::" + respCode);
response.setCommandStatus(respCode);
Integer comLength = new Integer(response.getCommandLength());
logger.debug("SMS -- CommandLength ::" + comLength);
response.setCommandLength(comLength);
logger.debug("SMS --- Response from SMSC" + response.toString());
return session;
} catch (WrongLengthOfStringException e)
{
logger.error("SMS -- Wrong length string exception"
+ e.getMessage());
} catch (ValueNotSetException e)
{
logger.error("SMS -- Value not set exception" + e.getMessage());
} catch (TimeoutException e)
{
logger.error("SMS -- Timeout exception " + e.getMessage());
} catch (PDUException e)
{
logger.error("SMS -- PDU exception " + e.getMessage());
} catch (WrongSessionStateException e)
{
logger.error("SMS -- Wrong Session exception " + e.getMessage());
} catch (IOException e)
{
logger.error("SMS --- Could not able to connect the host/port or Check the Username/Password for connection ::"
+ e.getMessage());
} catch (Exception e)
{
logger.error("SMS -- Error while sending SMS :: " + e.getMessage());
}
return null;
}
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);
logger.debug("SMS -------- Address :: " + addressInst);
return addressInst;
}
private Session unbind(Session session)
{
try
{
if (!_bound)
{
System.out.println("Not bound, cannot unbind.");
return session;
}
// send the request
logger.debug("Going to unbind.");
if (session.getReceiver().isReceiver())
{
logger.debug("SMS --- Unbinding --- It can take a while to stop the receiver.");
}
UnbindResp response = session.unbind();
logger.debug("Unbind response " + response.debugString());
_bound = false;
} catch (Exception e)
{
logger.debug("Unbind operation failed. " + e);
}
return session;
}
/**
* Creates a new instance of <code>EnquireSM</code> class. This PDU is used
* to check that application level of the other party is alive. It can be
* sent both by SMSC and ESME.
*
* See "SMPP Protocol Specification 3.4, 4.11 ENQUIRE_LINK Operation."
*
* #see Session#enquireLink(EnquireLink)
* #see EnquireLink
* #see EnquireLinkResp
*/
private void enquireLink(Session session)
{
try
{
EnquireLink request = new EnquireLink();
EnquireLinkResp response;
logger.debug("SMS ---- Enquire Link request "
+ request.debugString());
response = session.enquireLink(request);
logger.debug("SMS --- Enquire Link response "
+ response.debugString());
} catch (Exception e)
{
logger.debug("SMS ---- Enquire Link operation failed :: " + e);
}
}
private String[] splitMessage(String s, int size)
{
if (s == null || size <= 0)
return null;
int chunks = s.length() / size + ((s.length() % size > 0) ? 1 : 0);
String[] arr = new String[chunks];
for (int i = 0, j = 0, l = s.length(); i < l; i += size, j++)
arr[j] = s.substring(i, Math.min(l, i + size));
return arr;
}
}
Below is the parameter i need to consider while send/receive sms. But i really dont know whetherJAVA OpenSMPP APIuses this settings:
You can use the following code to query SMPP server to check what happend to you message (from https://github.com/OpenSmpp/opensmpp/blob/master/client/src/main/java/org/smpp/test/SMPPTest.java):
/**
* Creates a new instance of <code>QuerySM</code> class, lets you set
* subset of fields of it. This PDU is used to fetch information
* about status of already submitted message providing that you 'remember'
* message id of the submitted message. The message id is assigned
* by SMSC and is returned to you with the response to the submision
* PDU (SubmitSM, DataSM etc.).
*
* See "SMPP Protocol Specification 3.4, 4.8 QUERY_SM Operation."
* #see Session#query(QuerySM)
* #see QuerySM
* #see QuerySMResp
*/
private void query() {
debug.enter(this, "SMPPTest.query()");
try {
QuerySM request = new QuerySM();
QuerySMResp response;
// input values
messageId = getParam("Message id", messageId);
sourceAddress = getAddress("Source", sourceAddress);
// set values
request.setMessageId(messageId);
request.setSourceAddr(sourceAddress);
// send the request
System.out.println("Query request " + request.debugString());
if (asynchronous) {
session.query(request);
} else {
response = session.query(request);
System.out.println("Query response " + response.debugString());
messageId = response.getMessageId();
}
} catch (Exception e) {
event.write(e, "");
debug.write("Query operation failed. " + e);
System.out.println("Query operation failed. " + e);
} finally {
debug.exit(this);
}
}

issue in getting token id in android

I know that there are lot of questions about this but I couldn't figure out the solution from those questions.
I am getting null in a token from GCM. many people have done this using class, but I am doing
this in background thread in same class. It returns null in regId.
OnCreate
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
Log.e(TAG, "registering in background");
registerInBackground();
} else {
Log.e(TAG, "Notification Token : " + regid);
user.setNotificationToken(regid);
}
} else {
MyLog.i(TAG, "No valid Google Play Services APK found.");
}
RegisterInBackgroud() if device is not registered before.
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
Log.e(TAG, "doing in background");
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
if(gcm != null)
{
Log.e(TAG, "GCM is not null");
}
regid = gcm.register(SENDER_ID);
Log.e(TAG, "token id:" + regid);
msg = "Device registered, registration ID=" + regid;
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
}.execute(null, null, null);
}
I tried to log it bug it display null in regId. what could be the problem in this ?
Some how my app id was not working. Recreating app on google console generated a new id which i used in my project and it started working.

android: how to convert gps coordinates and send it to mysql server using post method

I'm trying to send data in my php server, but the data is in latitude and longitude format.
Here's the error: Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
private class sendlocation extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... args0)
{
double latlat = gps.getLatitude();
double longlong = gps.getLongitude();
String resultlat = Double.toString(latlat);
String resultlong = Double.toString(longlong);
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("Latitude",resultlat));
params.add(new BasicNameValuePair("Longitude",resultlong));
JSONObject json = jsonParser.makeHttpRequest(url_send_loc,"POST", params);
Log.d("Create Response", json.toString());
try
{
int success = json.getInt(TAG_SUCCESS);
if(success == 1)
{
Toast.makeText(getApplicationContext(),"Location Successfully sent: \nLat "+resultlat+" nLong" + resultlong ,Toast.LENGTH_LONG).show();
}
else
{ pdialog.dismiss();
Toast.makeText(getApplicationContext(), "Unknown error! Location not sent", Toast.LENGTH_LONG).show();
}
}catch(JSONException e)
{
e.printStackTrace();
}
return null;
};
}

Resources