Mqtt: Persist message on server side - mqtt

We decided to use mqtt protocol for chat module in our mobile application. I want to save messages of topic in server side also. But i saw,mqtt client is global here,so one way is i have to subscribe single instance of mqtt client to all topics and save messages in database. but is it right approach to do it. i am just worring about it.
private void buildClient(){
log.debug("Connecting... "+CLIENT_ID);
try {
mqttClient = new MqttClient(envConfiguration.getBrokerUrl(), CLIENT_ID);
} catch (MqttException e) {
log.debug("build client stopped due to "+e.getCause());
}
chatCallback = new ChatCallback();
mqttClient.setCallback(chatCallback);
mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(false);
}
#Override
public void connect() {
if(mqttClient == null || !mqttClient.getClientId().equals(CLIENT_ID)){
buildClient();
}
boolean tryConnecting = true;
while(tryConnecting){
try {
mqttClient.connect(mqttConnectOptions);
} catch (Exception e) {
log.debug("connection attempt failed "+ e.getCause() + " trying...");
}
if(mqttClient.isConnected()){
tryConnecting = false;
}else{
pause();
}
}
}
#Override
public void publish() {
boolean publishCallCompletedErrorFree = false;
while (!publishCallCompletedErrorFree) {
try {
mqttClient.publish(TOPIC, "hello".getBytes(), 1, true);
publishCallCompletedErrorFree = true;
} catch (Exception e) {
log.debug("error occured while publishing "+e.getCause());
}finally{
pause();
}
}
}
#Override
public void subscribe() {
if(mqttClient != null && mqttClient.isConnected()){
try {
mqttClient.subscribe(TOPIC, 2);
} catch (MqttException e) {
log.debug("subscribing error.."+e.getCause());
}
}
}
#Override
public void disconnect() {
System.out.println(this.mqttClient.isConnected());
try {
mqttClient.disconnect();
log.debug("disconnected..");
} catch (MqttException e) {
log.debug("erro occured while disconneting.."+e.getCause());
}
}

There are two possibilities how to solve this issue:
Write a MQTT client that subscribes to all topics using a wildcard (# in MQTT)
Write a broker plugin that does the job for you, depending on the broker implementation you're using
There is a good description of how to implement both options at the HiveMQ website, also describing limitations of the first option.

Related

exception occurs when iterating through futures

Can someone please explain to me what this piece of code does and how it can enter on the second catch clause, inside finally (without entering the first catch) and log this message "log.error("error while running closure", ee)" ?
try {
batches.each { batch -> futures << executorService.submit(['call':runClosure.curry(batch)] as Callable) }
} catch (Exception e) {
log.error("error: ", e)
} finally {
futures.each {
try {
it.get()
} catch (Exception ee) {
log.error("error while running closure", ee)
}
}
}
I have this piece of code that calls the method processBatch:
def runClosure = { batch ->
processBatch(batch)
}

How to properly update Android BillingFlowParams sku() to setSkuDetails()

here is the code can anyone tell how can I setSkuDetails()
as I was using vision one now I update it to 4
However, setSku and setType seem to be deprecated in the BillingFlowParams.Builder class. Instead, we should be using setSkuDetails(SkuDetails).
private void BillingFunction() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Establish connection to billing client
mBillingClient = BillingClient.newBuilder(MainActivity.this).setListener(MainActivity.this).build();
mBillingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(#NonNull BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
// The billing client is ready. You can query purchases here.
getPricesMonthlyTime();
getPricesYearlyTime();
getPricesONeTime();
}
}
#Override
public void onBillingServiceDisconnected() {
//TODO implement your own retry policy
Toast.makeText(MainActivity.this, getResources().getString(R.string.billing_connection_failure), Toast.LENGTH_SHORT);
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
continue_button.setOnClickListener(view -> {
if (select_radio_one.getVisibility() == View.VISIBLE) {
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSkuDetails()
.build();
BillingResult responseCode = mBillingClient.launchBillingFlow(MainActivity.this, flowParams);
brandDialogInAppPurchase.dismiss();
} else if (select_radio_two.getVisibility() == View.VISIBLE) {
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSkuDetails()
.build();
BillingResult responseCode = mBillingClient.launchBillingFlow(MainActivity.this, flowParams);
brandDialogInAppPurchase.dismiss();
} else if (select_radio_three.getVisibility() == View.VISIBLE) {
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSkuDetails()
.build();
BillingResult responseCode = mBillingClient.launchBillingFlow(MainActivity.this, flowParams);
brandDialogInAppPurchase.dismiss();
} else {
Toast.makeText(MainActivity.this, "Nothing selected", Toast.LENGTH_SHORT).show();
}
});
// queryPrefPurchases();
queryPurchases();
}
You should send the object skuDetail.
To do so you need to retrieve it by calling querySkuDetailsAsync().
fun querySkuDetails() {
val skuList = ArrayList<String>()
skuList.add("premium_upgrade")
skuList.add("gas")
val params = SkuDetailsParams.newBuilder()
params.setSkusList(skuList).setType(SkuType.INAPP)
// leverage querySkuDetails Kotlin extension function
val skuDetailsResult = withContext(Dispatchers.IO) {
billingClient.querySkuDetails(params.build())
}
// Process the result.
}

Critical Tunnel failure exception. How to solve this

I wrote the below code to send location coordinates to server:
setTitle("version 5.0");
Criteria criteria = new Criteria();
criteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setCostAllowed(true);
criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
// bc.setFailoverMode(GPSInfo.GPS_MODE_ssCDMA_MS_ASSIST, 2, 100);
try {
LocationProvider lp=LocationProvider.getInstance(criteria);
if(lp !=null)
{
Location loc=null;
// while(loc==null)
// {
loc=lp.getLocation(-1);
// }
if(loc!=null){
add(new EditField(loc.getQualifiedCoordinates().getLatitude()+"\n"+loc.getQualifiedCoordinates().getLongitude(),""));
}
else
add(new EditField("unable to find the location provider", ""));
}
else
{
add(new EditField("unable to find the location provider", ""));
}
} catch (LocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ButtonField b = new ButtonField("Send");
add(b);
b.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
try{
String url="http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true";
Dialog.alert(url);
ConnectionFactory factory = new ConnectionFactory();
// use the factory to get a connection
ConnectionDescriptor conDescriptor = factory.getConnection(url, TransportInfo.TRANSPORT_TCP_CELLULAR,null);
if ( conDescriptor != null ) {
HttpConnection conn = (HttpConnection) conDescriptor.getConnection();
Dialog.alert("http");
//conn.setRequestMethod(HttpConnection.GET);
Dialog.alert("conn.setre");
int responseCode = conn.getResponseCode();
Dialog.alert(Integer.toString(responseCode));
if(responseCode == HttpConnection.HTTP_OK)
{
Dialog.alert("OK");
InputStream data = conn.openInputStream();
StringBuffer raw = new StringBuffer();
byte[] buf = new byte[4096];
int nRead = data.read(buf);
while(nRead > 0)
{
raw.append(new String(buf, 0, nRead));
nRead = data.read(buf);
}
}
}
}catch(Exception e){
Dialog.alert(e.getMessage());
}
}
});
I am getting an exception Critical tunnel failure. But i am able to retrieve the location coordinates correctly. I am using blackberry 8520 with airtel sim which is enabled with data services. Actually this app worked well in the mobile with version 5.0. But it's not working in the mobile which i've upgraded from 4.6.1.3 to 5.0.0 what might be the problem? Please provide me a solution. thank you
I also tried the below url's:
http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true;apn=null
http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true;apn=airtelgprs.com
I also enabled apn settings in my mobile
It is because you haven't set up the apn correctly. As you are using direct tcp, the apn has to be set in order to connect to the network.
Also , network connections should be done on a separate thread.

Audio Recording Not Getting setRecordLocation()

I am trying to save audio at a specified device location on Button Click (which invokes run() method). This is my code.
public Audio() {
}
public void run()
{
try{
try{
_player = Manager.createPlayer("capture://audio?encoding=audio/amr");
}
catch(MediaException e)
{
Dialog.alert(e.toString());
}
_player.realize();
_rControl =(RecordControl)_player.getControl("RecordControl");
try{
**//Point 1//**_rControl.setRecordLocation("file:///Device Memory/samples/ringtones/recordTest1.amr");
}
catch(MediaException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
_rControl.startRecord();
_player.start();
System.out.println("<<--Successful-->>>");
}
catch(Exception e){e.printStackTrace();}
}
public void stop()
{
try{
if(_rControl != null)
{
_rControl.stopRecord();
try{
_rControl.commit();
}catch(Exception e){e.printStackTrace();}
_rControl = null;
}
if(_player != null)
{
_player.close();
_player=null;
}
}catch(Exception e){e.printStackTrace();}
}
In run() method, i am getting IOException at Point 1 where i am trying to set location for audio file. But when I tried this:
{
_rControl.setRecordLocation("file:///system/samples/ringtones/recordTest1.amr");
}
i found it working with 9550 simulator but not with 8900 simulator. So what location should i set to make this working with 8900 simulator and also 8900 blackberry device?
You should use:
javax.microedition.io.file.FileSystemRegistry.listRoots()
to get available root file systems on the device running the code.

how to check internet connection in java in blackberry

I want to check whether internet connection is there or not in blackberry device so that depending on the result I can call webservices to get data or upload data from my application
I have tried this one
CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_MDS))) ||
(CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B)) != false
If you want to check the internet connection, then send any url to the web service and check the HTTP Response. If HTTPResponse is 200 then only you are having internet connection. Do like this.......
try
{
factory = new HttpConnectionFactory();
url="Here put any sample url or any of your web service to check network connection.";
httpConnection = factory.getHttpConnection(url);
response=httpConnection.getResponseCode();
if(response==HttpConnection.HTTP_OK)
{
callback(response);
}else
{
callback(response);
}
} catch (Exception e)
{
System.out.println(e.getMessage());
callback(0);
}
Here "response"=200 then you have an internet connection. otherwise it is a connection problem. You can check this like below...........
public void callback(int i)
{
if(i==200)
{
//You can do what ever you want.
}
else
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
int k=Dialog.ask(Dialog.D_OK,"Connection error,please check your network connection..");
if(k==Dialog.D_OK)
{
System.exit(0);
}
}
});
}
}
Here System.exit(0); exit the application where ever you are.
Take these two classes
1)HttpConnectionFactory.java
2)HttpConnectionFactoryException.java
from this link:HttpConnection Classes

Resources