Get trouble with XMPPConnection - android

I try to get Room info related with login user with QuickBlox sdk. I edited chat sample app and try to grab room info according to this => http://www.igniterealtime.org/builds/smack/docs/latest/documentation/extensions/index.html
MultiUserChat.getRoomInfo, MultiUserChat.getJoinedRooms are not worked ! Connection is successful.NullPointer exception occur in Iterator<String> joinedRooms = MultiUserChat.getJoinedRooms(connection, "732374-5996#chat.quickblox.com");
public class MyChatController {
// ================= QuickBlox ===== Step 8 =================
// Get QuickBlox chat server domain.
// There will be created connection with chat server below.
public static final String CHAT_SERVER = QBChat.getChatServerDomain();
private XMPPConnection connection;
private ConnectionConfiguration config;
private Chat chat;
private String chatLogin;
private String password;
private String friendLogin;
private ChatManager chatManager;
public MyChatController(String chatLogin, String password) {
this.chatLogin = chatLogin;
this.password = password;
}
public void startChat(String buddyLogin) {
this.friendLogin = buddyLogin;
new Thread(new Runnable() {
#Override
public void run() {
// Chat action 1 -- create connection.
Connection.DEBUG_ENABLED = true;
config = new ConnectionConfiguration(CHAT_SERVER);
connection = new XMPPConnection(config);
try {
connection.connect();
connection.login(chatLogin, password);
// Chat action 2 -- create chat manager.
chatManager = connection.getChatManager();
// Chat action 3 -- create chat.
chat = chatManager.createChat(friendLogin, messageListener);
// Set listener for outcoming messages.
chatManager.addChatListener(chatManagerListener);
// Muc 2
if(connection != null){
// Get the rooms where user3#host.org has joined
Log.i("User Login =>", chatLogin);
Iterator<String> joinedRooms = MultiUserChat.getJoinedRooms(connection, "732374-5996#chat.quickblox.com");
/*while (joinedRooms.hasNext()) {
Log.i("Rooms =>", (String) joinedRooms.next());
}*/
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
}).start();
}
Logcat =>
12-27 00:38:23.259: E/AndroidRuntime(15395): FATAL EXCEPTION: Thread-3743
12-27 00:38:23.259: E/AndroidRuntime(15395): java.lang.NullPointerException
12-27 00:38:23.259: E/AndroidRuntime(15395): at org.jivesoftware.smackx.muc.MultiUserChat.getRoomInfo(MultiUserChat.java:237)
12-27 00:38:23.259: E/AndroidRuntime(15395): at com.quickblox.sample.chat.MyChatController$3.run(MyChatController.java:95)
12-27 00:38:23.259: E/AndroidRuntime(15395): at java.lang.Thread.run(Thread.java:856)

New SDK and chat sample with several improvements have been released.

We almost finished working on our new sdk. We added new features for xmmp chat, increased stability. The sample will be released soon. You can try to use it for your project.

Related

Error while processing request on Azure

I have an app connected with Azure backend. I created a login and some api calls 2 months ago. They worked fine until a few days ago and then it starts to fail "sometimes".
The login log onFailure says: Error while authenticating user
The callback log onFailure says: Error while processing request
And the cause of both says : stream was reset: PROTOCOL_ERROR
This post is to similar to this but didn't work.
Some code here:
LoginFragment.java
private void login(String email, String password){
loginProgressBar.setVisibility(View.VISIBLE);
try {
JsonObject params = new JsonObject();
params.addProperty("Username", email);
params.addProperty("Password", password);
ListenableFuture<MobileServiceUser> listenable = Client.logIn(getContext(), params);
Futures.addCallback(listenable, new FutureCallback<MobileServiceUser>() {
#Override
public void onSuccess(MobileServiceUser mobileServiceUser) {
loginProgressBar.setVisibility(View.GONE);
SharedPreferences settings = getActivity().getSharedPreferences(Client.MS_USER,0);
SharedPreferences.Editor editor = settings.edit();
Client.clientId = mobileServiceUser.getUserId();
Client.token = mobileServiceUser.getAuthenticationToken();
editor.putString(Client.MS_USER_ID, Client.clientId);
editor.putString(Client.MS_AUTH_TOKEN, Client.token);
editor.apply();
Client.getInstance(getContext()).setCurrentUser(mobileServiceUser);
Intent i = new Intent(getContext(), MainActivity.class);
startActivity(i);
}
#Override
public void onFailure(Throwable t) {
loginProgressBar.setVisibility(View.GONE);
Throwable t2 = t.getCause();
Throwable t3 = t2.getCause();
Log.e("LoginFail", t.getMessage());
Log.e("LoginFail", t2.getMessage());
if(t3 != null){
Log.e("LoginFail", t3.getMessage());
}
Toast.makeText(getContext(), getResources().getString(R.string.bad_login), Toast.LENGTH_LONG).show();
}
}, MoreExecutors.directExecutor());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
Client.java
public class Client {
public static final String MS_USER = "MS_USER";
public static final String MS_USER_ID = "MS_USER_ID";
public static final String MS_AUTH_TOKEN = "MS_AUTH_TOKEN";
public static String clientId;
public static String token;
private static MobileServiceClient instance = null;
public static MobileServiceClient getInstance(Context context) {
if (instance ==null){
try {
instance = new MobileServiceClient(Env.AZURE_URL, context);
instance.setAndroidHttpClientFactory(() -> {
OkHttpClient client = new OkHttpClient();
client.setReadTimeout(20, TimeUnit.SECONDS);
client.setWriteTimeout(20, TimeUnit.SECONDS);
return client;
});
} catch (MalformedURLException e) {
e.printStackTrace();
}
} else{
instance.setContext(context);
}
return instance;
}
public static ListenableFuture<MobileServiceUser> logIn(Context context, JsonObject parameters) throws MalformedURLException {
String deviceID = "gcm:" + Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
parameters.addProperty("device_id", deviceID);
parameters.addProperty("device_dateTime", Env.DATE_FORMAT.format(new Date()));
parameters.addProperty("device_timeZone", API.getTimezone());
parameters.addProperty("device_language", Env.LANGUAGE);
parameters.addProperty("app", Env.APP_NAME);
return getInstance(context).login("auth", parameters);
}
public static ListenableFuture<JsonElement> callApi(Context context, String apiName, JsonObject parameters, String httpMethod){
if(httpMethod.equals("POST")){
String deviceID = "gcm:" + Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
parameters.addProperty("user_id", Client.clientId);
parameters.addProperty("device_id", deviceID);
parameters.addProperty("device_dateTime", Env.DATE_FORMAT.format(new Date()));
parameters.addProperty("device_timeZone", API.getTimezone());
parameters.addProperty("device_language", Env.LANGUAGE);
parameters.addProperty("app", Env.APP_NAME);
parameters.addProperty("role", "Patient");
return getInstance(context).invokeApi(apiName, parameters, httpMethod, null);
} else {
return getInstance(context).invokeApi(apiName, null, httpMethod, null);
}
}
This is probably related to an issue in Azure App Service that is weirdly enough not reported on the public Azure status page.
The message that affected Azure client received was (quoted from the link above):
Starting at 02:00 UTC on 3 Apr 2018, you have been identified as a
customer using App Services who may have received connection failure
notifications when using Android apps with older HTTP clients or
desktop browsers using cross-site scripting calls. Engineers have
identified an issue with a recent deployment and are investigating
mitigation options. Customers experiencing this issue can
self-mitigate by updating the site config setting "http20Enabled" to
false via resources.azure.com. Instructions on how to update site
config can be found here:
https://azure.microsoft.com/en-us/blog/azure-resource-explorer-a-new-tool-to-discover-the-azure-api/
Go to https://resources.azure.com/
Make sure you are in Read/Write mode by clicking in the option to the
left of your name.
Find the affected site and browse to Config > Web:
https://resources.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//config/web
Change the property: "http20Enabled": from true to false by clicking
in Edit properties, Update to “false” and then clicking PUT to save
change.
If you have tried these steps and are continuing to experience issues
with your App Service, please create a technical support ticket to
further troubleshoot: aka.ms/azsupt. This message will be closed in 7
days.

Xmpp + openfire + server acknowledgement to the sender

I'm developing IM application.
I want to get acknowledgement at the time of
when message is received by the Openfire server
I have used below gradles
//XMPP Gradles
compile 'org.igniterealtime.smack:smack-android:4.1.0'
compile 'org.igniterealtime.smack:smack-tcp:4.1.0'
compile 'org.igniterealtime.smack:smack-im:4.1.0'
compile 'org.igniterealtime.smack:smack-extensions:4.1.0'
Note: I have already gone through each and every StackOverflow links and conclude that Openfire doesn't support XEP-0184, and it describes a mechanism for delivery receipts only.
I have also tried DeliveryReceiptManager and set their addReceiptReceivedListener but its not working.
Any workarounds or suggestions will be appreciated.
It is better to attach a common listener to every sent message and update your database(and hence your UI) accordingly.
Define a random UUID for each outgoing message:
String stanzaId = UUID.randomUUID().toString()
Attach the listener to your message:
xmppTcpConnection.addStanzaIdAcknowledgedListener(stanzaId , new StanzaListener()
{
#Override
public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException
{
// You can match your stanzaId here!
// packet.getStanzaId()
}
});
add:
compile "org.igniterealtime.smack:smack-tcp:4.2.0"
to get XMPPTCPConnection object.
Update: Try adding the listener before calling connect() on the xmppTcpConnection object.
while sending message attach DeliveryReceiptRequest.addTo(msg);
like this
Message msg = new Message(oppositeUserId, Message.Type.chat);
msg.setBody(mMessageBody);
msg.setStanzaId(messageId);
msg.setFrom(loginUserId);
DeliveryReceiptRequest.addTo(msg);
mXMPPTCPConnection.sendStanza(msg);
XmppDeliveryReceiptManager.java
public class XmppDeliveryReceiptManager implements ReceiptReceivedListener {
private static final String TAG = XmppDeliveryReceiptManager.class.getSimpleName();
Context mContext;
public XmppDeliveryReceiptManager(Context mContext) {
this.mContext = mContext;
Log.d(TAG, "XmppDeliveryReceiptManager : initialized ");
}
#Override
public void onReceiptReceived(String fromJid, String toJid, String receiptId, Stanza receipt) {
Log.d(TAG, "onReceiptReceived : receiptId = " + receiptId);
// do need full with "receiptId"
}
}
add this to your XMPP configuration
/* Add XMPP DeliveryReceiptManager */
ProviderManager.addExtensionProvider(DeliveryReceipt.ELEMENT,
DeliveryReceipt.NAMESPACE, new DeliveryReceipt.Provider());
ProviderManager.addExtensionProvider(DeliveryReceiptRequest.ELEMENT,
new DeliveryReceiptRequest().getNamespace(), new DeliveryReceiptRequest.Provider());
mXmppDeliveryReceiptManager = new XmppDeliveryReceiptManager(mContext);
mDeliveryReceiptManager = DeliveryReceiptManager.getInstanceFor(mXMPPTCPConnection);
mDeliveryReceiptManager.setAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.always);
mDeliveryReceiptManager.addReceiptReceivedListener(mXmppDeliveryReceiptManager);

AWS IoT Android application over MQTT throws MqttException (0) - java.io.IOException: Already connected

I am trying to use 'Authenticate using Cognito-Identity with Cognito user pool' in my Android application. My Cognito user pool authentication works well, when I run that separately and I had seen a JWTToken as well. When I run the the 'PubSub' sample application with Unauthenticated role, it worked as expected. When I integrate these two features in one application, the application threw following error.
W/System.err: MqttException (0) - java.io.IOException: Already connected
W/System.err: at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
W/System.err: at java.lang.Thread.run(Thread.java:761)
W/System.err: Caused by: java.io.IOException: Already connected
W/System.err: at java.io.PipedOutputStream.connect(PipedOutputStream.java:100)
W/System.err: at java.io.PipedInputStream.connect(PipedInputStream.java:195)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketReceiver.<init>(WebSocketReceiver.java:42)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketSecureNetworkModule.start(WebSocketSecureNetworkModule.java:78)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
W/System.err: ... 1 more
I have been trying to resolve this issue since last Thursday and still stuck at the same place. Really No idea where should i check.!
I am adding my Authentication(Cognito user pool authentication) activity and Connect activity.
AmazonCognitoIdentityProviderClient identityProviderClient = new
AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), new ClientConfiguration());
identityProviderClient.setRegion(Region.getRegion(Regions.US_WEST_2));
CognitoUserPool userPool = new CognitoUserPool(getApplicationContext(), "us-west-2_ghtcc6ho9", "4t0mk45hNso69dp2j4jvel5ghm", "1jmq0lhhq721oif9k6nug31c29i760vihua8hvrgu5umfr2a1vd7", identityProviderClient);
cogUser = userPool.getUser();
authenticationHandler = new AuthenticationHandler() {
#Override
public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
String ids = userSession.getIdToken().getJWTToken();
Log.d("MyToken","session id___"+userSession.getIdToken().getExpiration()+"___"+userSession.getIdToken().getIssuedAt());
Intent pubSub = new Intent(MainActivity.this, PubSubActivity.class);
pubSub.putExtra("token",""+ids);
startActivity(pubSub);
//MainActivity.this.finish();
}
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
Log.d("MyToken","getAuthenticationDetails");
AuthenticationDetails authenticationDetails = new AuthenticationDetails("shone", "172737", null);
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
// Allow the sign-in to continue
authenticationContinuation.continueTask();
}
#Override
public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) {
Log.d("MyToken","getMFACode");
multiFactorAuthenticationContinuation.continueTask();
}
#Override
public void authenticationChallenge(ChallengeContinuation continuation) {
Log.d("MyToken","authenticationChallenge"+continuation.getChallengeName());
newPasswordContinuation.continueTask();
}
#Override
public void onFailure(Exception exception) {
exception.printStackTrace();
Log.d("MyToken","onFailure");
}
};
cogUser.getSessionInBackground(authenticationHandler);
When It reaches 'OnSuccess' I am launching my connect activity and passing my session token along with the Intent. Moving to the next activity
private static final String COGNITO_POOL_ID = "us-west-2:a153a090-508c-44c0-a9dd-efd450298c4b";
private static final Regions MY_REGION = Regions.US_WEST_2;
AWSIotMqttManager mqttManager;
String clientId;
AWSCredentials awsCredentials;
CognitoCachingCredentialsProvider credentialsProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
if(null == intent){
Toast.makeText(getApplicationContext(), "Token is null", Toast.LENGTH_SHORT).show();
}else {
token = intent.getStringExtra("token");
}
clientId = UUID.randomUUID().toString();
credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
COGNITO_POOL_ID,
MY_REGION
);
mqttManager = new AWSIotMqttManager(clientId, CUSTOMER_SPECIFIC_ENDPOINT);
Map loginsMap = new HashMap();
loginsMap.put("cognito-idp.us-west-2.amazonaws.com/us-west-2_ghtcc6ho9", token);
credentialsProvider.setLogins(loginsMap);
Log.d("SESSION_ID", ""+token);
new Thread(new Runnable() {
#Override
public void run() {
credentialsProvider.refresh();
awsCredentials = credentialsProvider.getCredentials();
Log.d("SESSION_ID B: ", ""+awsCredentials.getAWSAccessKeyId());
Log.d("SESSION_ID C: ", ""+awsCredentials.getAWSSecretKey());
}
}).start();
}
View.OnClickListener connectClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "clientId = " + clientId);
try {
mqttManager.connect(credentialsProvider, new AWSIotMqttClientStatusCallback() {
#Override
public void onStatusChanged(final AWSIotMqttClientStatus status,
final Throwable throwable) {
Log.d(LOG_TAG, "Status = " + String.valueOf(status)+"______"+((null !=throwable)?throwable.getMessage():""));
runOnUiThread(new Runnable() {
#Override
public void run() {
if (status == AWSIotMqttClientStatus.Connecting) {
tvStatus.setText("Connecting...");
} else if (status == AWSIotMqttClientStatus.Connected) {
tvStatus.setText("Connected");
} else if (status == AWSIotMqttClientStatus.Reconnecting) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
}
tvStatus.setText("Reconnecting");
} else if (status == AWSIotMqttClientStatus.ConnectionLost) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
throwable.printStackTrace();
}
tvStatus.setText("Disconnected");
} else {
tvStatus.setText("Disconnected");
}
}
});
}
});
} catch (final Exception e) {
Log.e(LOG_TAG, "Connection error.", e);
}
}
};
What is wrong in my code? Why it throws exception when the MQTT connect is being invoked? Any help would be appreciated.
I beat my head up with this almost a week.
Full course of action ->
After succesfull login you will have a jwt token
String idToken = cognitoUserSession.getIdToken().getJWTToken();
put it into a map
Map<String, String> logins = new HashMap<String, String>();
//fill it with Cognito User token
logins.put("cognito-idp.<REGION>.amazonaws.com/<COGNITO_USER_POOL_ID>", idToken);
then use it to set in two places (not stated in any documentation!)
CognitoCachingCredentialsProvider credentialsProvider = new
CognitoCachingCredentialsProvider(context, IDENTITY_POOL_ID, REGION);
credentialsProvider.setLogins(logins);
and
AmazonCognitoIdentity cognitoIdentity = new AmazonCognitoIdentityClient(credentialsProvider);
GetIdRequest getIdReq = new GetIdRequest();
getIdReq.setLogins(logins); //or if you have already set provider logins just use credentialsProvider.getLogins()
getIdReq.setIdentityPoolId(COGNITO_POOL_ID);
GetIdResult getIdRes = cognitoIdentity.getId(getIdReq);
after that you still nedd to make some call
AttachPrincipalPolicyRequest attachPolicyReq = new AttachPrincipalPolicyRequest(); //in docs it called AttachPolicyRequest but it`s wrong
attachPolicyReq.setPolicyName("allAllowed"); //name of your IOTAWS policy
attachPolicyReq.setPrincipal(getIdRes.getIdentityId());
new AWSIotClient(credentialsProvider).attachPrincipalPolicy(attachPolicyReq);
and only after that you can enable connect button and continue like that
mqttManager.connect(credentialsProvider, new AWSIotMqttClientStatusCallback() {
Really for this small piece of code i spent a lot of time...
I was also getting same error -
Feb 27, 2019 10:23:09 AM com.amazonaws.services.iot.client.mqtt.AwsIotMqttConnectionListener onFailure
WARNING: Connect request failure
MqttException (0) - java.io.IOException: Already connected
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: Already connected
at java.io.PipedOutputStream.connect(PipedOutputStream.java:100)
but the problem was different.
First of all, you do not need to call attachPrincipalPolicy from code. You can use the command line as well. You can do something like -
aws iot attach-principal-policy --principal us-east-1:1c973d17-98e6-4df6-86bf-d5cedc1fbc0d --policy-name "thingpolicy" --region us-east-1 --profile osfg
You will get the principal ID from identity browser of your identity pool. Now lets come to the error -
To successfully connect to mqtt with authenticated Cognito credentials, you need 2 correct policies -
Authenticated role corresponding to your identity pool should allow all mqtt operations.
AWS IoT policy should allow the same operations and you need to associate your cognito identity with this policy. We use attachPrincipalPolicy to do so.
If anyone step is missed we get above error. I agree the error is misleading - Already connected makes no sense to me for this. I would normally think it has to do with clientId, which should be unique. But anyways hopefully AWS folks would make this better at some point.
For my particular case issue was point 1. Though my IoT policy had all the required permissions, the auth role corresponding to the identity pool did not. So make sure you do that.
I have created a youtube video to show this as well: https://www.youtube.com/watch?v=j2KJVHGHaFc
When a client connected to broker it has a unique client ID. If clients tried to connect with same client id then this error occur. Use different client IDs like foo1, foo2, foo3, etc.

Multiuser chat using smack not getting message listner

I am developing chat app using smack libary. I have issue in group chat. In my app i am creating group and in that members are auto joined.i want to notify all user when i send message in group even if they had not initiated chat.My code is as follow in that i have place listener in init method but unable to receive message.
//Initialize
public void init(String userId, String pwd, Context context) throws SmackException.NotConnectedException {
this.mUserName = userId;
this.mPassWord = pwd;
this.mContext = context;
sessionManager = new SessionManager(context);
if (userId.contains("#")) {
this.mUserName = userId.split("#")[0];
}
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(mUserName, mPassWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setServiceName(XMPPCredential.SERVICE);
configBuilder.setHost(XMPPCredential.HOST);
configBuilder.setPort(XMPPCredential.PORT);
configBuilder.setResource("");
// configBuilder.setDebuggerEnabled(true);
mConnection = new XMPPTCPConnection(configBuilder.build());
PingManager pingManager = PingManager.getInstanceFor(mConnection);
pingManager.setPingInterval(300); // 2.5 min
pingManager.registerPingFailedListener(this);
mChatmanager.getInstanceFor(mConnection).addChatListener(this);
multiUserChatManager = MultiUserChatManager.getInstanceFor(mConnection);
mConnection.addAsyncStanzaListener(this, null);
mConnection.addSyncStanzaListener(this,null);
ReconnectionManager.getInstanceFor(mConnection).enableAutomaticReconnection();
mConnection.addConnectionListener(this);
// Connect with XMPP server
connectConnection(context);
}
Each MultiUserChat needs to add a Listener like this:
MultiUserChat muc = MultiUserChatManager.getInstanceFor(mConnection).getMultiUserChat( mucJid );
muc.addMessageListener(new MessageListener()...);

How to connect Android on RabbitMQ?

I'd like to use RabbitMQ client from an android App.
From the server side, i use SpringBoot with spring AMQP. RabbitMQ (rabbitmq_server-3.4.3) is installed correctly and an integration test valid the server behaviour.
The difficult part is when i try to create a connection from RabbitMQ connectionFactory inside my android project.
I get this exception :
failed to connect to localhost/127.0.0.1 (port 5672):
connect failed: ECONNREFUSED (Connection refused)
In android manifest, Internet permission is set :
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Here is my code :
public class LoadingTask extends AsyncTask<String, Integer, Integer> {
private static String replyQueue = "REPLY_QUEUE";
public interface LoadingTaskListener {
void onResourceLoaded();
}
private final ProgressBar progressBar;
private final LoadingTaskListener loadingTaskListener;
private ConnectionFactory connectionFactory;
public LoadingTask(ProgressBar progressBar, LoadingTaskListener loadingTaskListener) {
this.progressBar = progressBar;
this.loadingTaskListener = loadingTaskListener;
this.connectionFactory = new ConnectionFactory();
connectionFactory.setAutomaticRecoveryEnabled(true);
}
#Override
protected Integer doInBackground(String... params) {
try {
/*init rabbitMQ Context*/
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
channel.basicQos(1);
channel.queueDeclare(DATA_QUEUE.getName(), false, false, false, null);
AMQP.Queue.DeclareOk q = channel.queueDeclare();
channel.queueBind(q.getQueue(), "amq.fanout", "chat");
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(replyQueue, true, consumer);
/* initiate RPC */
String corrId = java.util.UUID.randomUUID().toString();
AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
.correlationId(corrId)
.replyTo(replyQueue)
.build();
AmqpRequest request = new AmqpRequest(LIST_IMAGE);
Gson gson = new Gson();
String jsonRequest = gson.toJson(request);
channel.basicPublish(MAIN_EXCHANGE.getName(), DATA_QUEUE.getRoutingKey(), props, jsonRequest.getBytes());
String response;
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
if (delivery.getProperties().getCorrelationId().equals(corrId)) {
response = new String(delivery.getBody());
break;
}
}
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Dummy Data until i can't connect to rabbitMQ
return 1234;
}
}
Is it really possible to connect Android on RabbitMQ, or should i use a kind of http bridge ?
Could anyone provide me an exemple for both http bridge or RabbitMQ connection.
Thank you

Categories

Resources