Nearby connections 2.0 simple files exchange app - google-play-services

I'm trying to write simple android file exchange application, mostly using snippets from https://developers.google.com/nearby/connections/android/exchange-data and Walkietalkie app.
But I'm stuck on transferring File payload second sendPayload, onPayloadTransferUpdate called only on sending side. Discovering, advertising, connecting to the endpoint, everything works fine. The sender is "sending", but Reciever gets only string message with id and filename and waits (onPayloadTransferUpdate called only 2 times for the first sendPayload) and then nothing, disconnects after sender finished transferring.
public void sendFile(String uri) {
File file = new File(uri);
if (file.exists() && mEstablishedConnections.values().size() > 0) {
for (Endpoint endpoint : mEstablishedConnections.values()) {
try {
// Open the ParcelFileDescriptor for this URI with read access.
ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(Uri.fromFile(file), "r");
Payload filePayload = Payload.fromFile(pfd);
// Construct a simple message mapping the ID of the file payload to the desired filename.
String payloadFilenameMessage = filePayload.getId() + ":" + Uri.fromFile(file).getLastPathSegment();
// Send this message as a bytes payload.
Nearby.Connections.sendPayload(mGoogleApiClient,
endpoint.getId(),
Payload.fromBytes(payloadFilenameMessage.getBytes("UTF-8")));
// Finally, send the file payload.
Nearby.Connections.sendPayload(mGoogleApiClient,
endpoint.getId(),
filePayload);
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
} else {
Log.e(TAG, "sendFile: EstablishedConnections == 0");
}
}
private final PayloadCallback mPayloadCallback = new PayloadCallback() {
#Override
public void onPayloadReceived(String endpointId, Payload payload) {
Log.d(TAG, String.format("onPayloadReceived(endpointId=%s, payload=%s)", endpointId, payload));
try {
if (payload.getType() == Payload.Type.BYTES) {
Log.d(TAG, "onPayloadReceived: Payload.Type.BYTES");
String payloadFilenameMessage = new String(payload.asBytes(), "UTF-8");
Log.d(TAG, "onPayloadReceived: BYTES " + payloadFilenameMessage);
addPayloadFilename(payloadFilenameMessage);
} else if (payload.getType() == Payload.Type.FILE) {
// Add this to our tracking map, so that we can retrieve the payload later.
incomingFilePayloads.put(payload.getId(), payload);
Log.d(TAG, "onPayloadReceived: Payload.Type.FILE");
} else if (payload.getType() == Payload.Type.STREAM) {
//payload.asStream().asInputStream()
Log.d(TAG, "onPayloadReceived: Payload.Type.STREAM");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onPayloadTransferUpdate(String endpointId, PayloadTransferUpdate update) {
Log.d(TAG, String.format("onPayloadTransferUpdate(endpointId=%s, update=%s)",
endpointId, update));
switch(update.getStatus()) {
case PayloadTransferUpdate.Status.IN_PROGRESS:
break;
case PayloadTransferUpdate.Status.SUCCESS:
Log.d(TAG, "onPayloadTransferUpdate: SUCCESS");
Payload payload = incomingFilePayloads.remove(update.getPayloadId());
if (payload != null && payload.getType() == Payload.Type.FILE) {
// Retrieve the filename that was received in a bytes payload.
String newFilename = filePayloadFilenames.remove(update.getPayloadId());
java.io.File payloadFile = payload.asFile().asJavaFile();
// Rename the file.
payloadFile.renameTo(new File(payloadFile.getParentFile(), newFilename));
}
break;
case PayloadTransferUpdate.Status.FAILURE:
Log.d(TAG, "onPayloadTransferUpdate: FAILURE");
break;
}
}
};
Is there a working example apart from google sample walkietalkie?
Sender
D/ShareService: sendFile: filename message -7668342386822656500:a73ecba18dc6c8506ed89c1ed47c9948.mp4
D/ShareService: onPayloadTransferUpdate(endpointId=osUc, update=com.google.android.gms.nearby.connection.PayloadTransferUpdate#e16fc0a8)
D/ShareService: onPayloadTransferUpdate: 57
D/ShareService: onPayloadTransferUpdate: 1048576
D/DiscoveryActivity: onNext: ShareState{state='Sending ', stateCode=800}
D/ShareService: onPayloadTransferUpdate(endpointId=osUc, update=com.google.android.gms.nearby.connection.PayloadTransferUpdate#813731ce)
D/ShareService: onPayloadTransferUpdate: 1055744
D/DiscoveryActivity: onNext: ShareState{state='Sending ', stateCode=800}
D/ShareService: onPayloadTransferUpdate(endpointId=osUc, update=com.google.android.gms.nearby.connection.PayloadTransferUpdate#81372a4c)
11-01 07:35:20.790 D/ShareService: onPayloadTransferUpdate: SUCCESS
11-01 07:35:41.587 D/ShareService: disconnectedFromEndpoint(endpoint=Endpoint{id=osUc, name=87389})
11-01 07:35:41.587 D/ShareService: onEndpointDisconnected
Reciever
D/ShareService: onConnectionResponse(endpointId=ABVq, result=com.google.android.gms.nearby.connection.ConnectionResolution#9edd5e3)
D/ShareService: connectedToEndpoint(endpoint=Endpoint{id=ABVq, name=08043})
D/ShareService: onEndpointConnected
D/ShareService: stopDiscovering
D/ShareService: stopAdvertising
D/ShareService: onPayloadReceived(endpointId=ABVq, payload=com.google.android.gms.nearby.connection.Payload#516155e)
D/ShareService: onPayloadReceived: Payload.Type.BYTES
D/ShareService: onPayloadReceived: BYTES -7668342386822656500:a73ecba18dc6c8506ed89c1ed47c9948.mp4
D/ShareService: onPayloadTransferUpdate(endpointId=ABVq, update=com.google.android.gms.nearby.connection.PayloadTransferUpdate#ba6f47ac)
D/ShareService: onPayloadTransferUpdate: 57
D/ShareService: onPayloadTransferUpdate(endpointId=ABVq, update=com.google.android.gms.nearby.connection.PayloadTransferUpdate#ba6f402a)
11-01 08:10:52.525 D/ShareService: onPayloadTransferUpdate: SUCCESS
11-01 08:11:12.355 D/ShareService: disconnectedFromEndpoint(endpoint=Endpoint{id=ABVq,name=08043})
D/ShareService: onEndpointDisconnected
onPayloadTransferUpdate: SUCCESS for first string transfer
delay
Payload bytePayload = outgoingPayloads.remove(update.getPayloadId());
if (bytePayload != null && bytePayload.getType() == Payload.Type.BYTES) {
if (endpnt != null && filePayload != null) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Nearby.Connections.sendPayload(mGoogleApiClient,
endpnt.getId(),
filePayload);
}
}
file:///data/data/com.package.name/files/folder/a73ecba18dc6c8506ed89c1ed47c9948.mp4
sources https://github.com/salexwm/FilesExchange

I can provide a working example if you need one, but you almost have it. Some pointers:
Send the FILE payload only after the BYTE header has fully sent, in onPayloadTransferUpdate(SUCCESS). Order isn't guaranteed for payloads of different types.
Don't disconnect until you get onPayloadTransferUpdate(SUCCESS) for the FILE payload. If you disconnect during transmission, it won't fully send.
You should be doing Uri.parse(uri), not Uri.fromFile(new File(uri)).

Related

onMessageReceived method is not called, when app is not open

I have implemented FCM in my app, and I need to pass some data from Firebase service to Activity. I have implemented the following code, which works fine, when the app is in foreground(open). When the app is killed or in background, onMessageReceived method is not called, and the launcher activity is loaded while click on the push notification. Also, when the app is open, push message is blank. Kindly advise what I have done wrong. FYI, from backend, they are sending data payload, not notification.
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
public FirebaseMessagingService() {
}
private static final String TAG = com.google.firebase.messaging.FirebaseMessagingService.class.getSimpleName();
public static String CHAT_PUSH_NOTIFICATION_INTENT = "chatPushNotificationIntent";
private PreferencesManager preferencesManager;
#Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("push token >>", s);
String reliableIdentifier = FirebaseInstanceId.getInstance().getId();
FCMPreferencesManager pref = FCMPreferencesManager.getInstance(this);
if (pref != null) {
pref.setStringValue(FCMPreferencesManager.FCM_KEY_VALUE, s);
pref.setStringValue(FCMPreferencesManager.DEVICE_ID, reliableIdentifier);
}
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
try {
preferencesManager = PreferencesManager.getInstance(this);
int userId = preferencesManager.getIntValue(PreferencesManager.LOGIN_USER_ID);
Log.e("onMessage received >>", "inside service");
Log.e("userId >>", userId + "");
if (userId > 0) {
Log.e("remote message >>", remoteMessage.getNotification().getBody() + "");
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
handleDataMessage(json);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void classApprovedNotification(int jobId, String stage) {
if (!Utils.isAppIsInBackground(getApplicationContext())) {
Intent pushNotification = new Intent(Constants.PUSH_NOTIFICATION_INTENT);
pushNotification.putExtra("jobId", jobId);
pushNotification.putExtra("stage", stage);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
}
}
private void handleDataMessage(JSONObject json) {
try {
Log.e("total json >> ", json.toString());
JSONObject data = json.optJSONObject("data");
Log.e("data >> ", data.toString());
String title = data.optString("title");
String message = data.optString("message");
Log.e("title >>", title);
Log.e("message >>", message);
localNotification(data, title, message, false);
} catch (Exception e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
}
}
private void localNotification(JSONObject data, String title, String message, boolean isSendBird) {
int type = 0, groupId = 0, classId = 0, jobId = 0;
String stage = "";
int notificationId = (int) System.currentTimeMillis();
int userId = preferencesManager.getIntValue(PreferencesManager.LOGIN_USER_ID);
String className = "", fileName = "";
if (data != null) {
jobId = data.optInt("job_id");
stage = data.optString("stage", "");
}
Log.e("jobId in service >>", jobId + "");
Log.e("stage in service >>", stage);
Intent intent = new Intent(FirebaseMessagingService.this, VendorHomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("jobId", jobId);
intent.putExtra("stage","stage");
int requestID = (int) System.currentTimeMillis();
final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
requestID,
intent,
PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
);
String channelId = "";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.fyxt_logo)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/* NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);*/
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(notificationId /* ID of notification */, notificationBuilder.build());
try {
PowerManager.WakeLock screenLock = null;
if ((getSystemService(POWER_SERVICE)) != null) {
screenLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "OOTUSER:WAKE");
screenLock.acquire(10 * 60 * 1000L /*10 minutes*/);
screenLock.release();
}
} catch (Exception e) {
e.printStackTrace();
}
classApprovedNotification(jobId, stage);
}
}
In my Activity, I have the following code.
private BroadcastReceiver notificationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
jobIdFromNotification = intent.getIntExtra("jobId", 0);
stageFromNotification = intent.getStringExtra("stage");
Log.e("jobIdFromNotification >>", jobIdFromNotification + "");
Log.e("stageFromNotification >>", stageFromNotification);
prefManager.setIntValue(PreferencesManager.JOB_ID_IN_PREF, jobIdFromNotification);
prefManager.setStringValue(PreferencesManager.JOB_STAGE_IN_PREF, stageFromNotification);
classApprovedViewUpdate();
}
};
private void classApprovedViewUpdate() {
if (jobIdFromNotification > 0) {
fragmentInteractionCallback = (BaseFragment.FragmentInteractionCallback) this;
Log.e("inside push receiver update ", "sfs");
if (stageFromNotification.trim().equalsIgnoreCase(Constants.STAGE_TICKET_APPROVAL)) {
sendActionToActivity(ACTION_CREATE_MAINTENANCE_REQUEST, currentTab, true, fragmentInteractionCallback);
}
}
}
Edit:
data payload:
{
"data": {
"type": 0,
"job_id": 123,
"stage": "STAGE_TICKET_APPROVAL",
}

spring boot file uploading executes twice when MultipartException occurs

I want to upload files using spring-boot, and I have configured the properties right, and I also ensure the controller is correct, but the strange thing is the controller executed twice when I tried to upload a file larger exceed the limitation, what I expect is an error json message, and what I got is no response under the Postman.
Here is my controller,
#RestController
public class FileUploadController implements HandlerExceptionResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class);
private static final String UPLOAD_PATH = "upload";
#ResponseBody
#RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = "multipart/form-data", produces = "application/json;charset=UTF-8")
public String upload(final MultipartFile file) {
try {
final Result<String> result = new Result<>();
if (file.isEmpty()) {
result.setSuccess(false);
result.setMessage("file is empty");
return Constants.OBJECT_MAPPER.writeValueAsString(result);
}
final File outputFile = new File(UPLOAD_PATH, UUID.randomUUID().toString());
FileUtils.writeByteArrayToFile(outputFile, file.getBytes());
result.setSuccess(true);
result.setMessage(outputFile.toString());
return Constants.OBJECT_MAPPER.writeValueAsString(result);
} catch (final Exception ex) {
LOGGER.error(ex.getMessage(), ex);
return ExceptionResultBuilder.build(ex);
}
}
#Override
public ModelAndView resolveException(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) {
final ModelAndView modelAndView = new ModelAndView();
modelAndView.setView(new MappingJackson2JsonView());
final Map<String, Object> map = new HashMap<>();
map.put("success", false);
if (ex instanceof MultipartException) {
// if (LOGGER.isDebugEnabled()) {
LOGGER.info(ex.getMessage(), ex);
// }
final Throwable rootCause = ((MultipartException) ex).getRootCause();
if (rootCause instanceof SizeLimitExceededException) {
map.put("message", "request too large");
} else if (rootCause instanceof FileSizeLimitExceededException) {
map.put("message", "file too large");
} else {
map.put("message", "其他异常: " + rootCause.getMessage());
}
} else {
LOGGER.error(ex.getMessage(), ex);
}
modelAndView.addAllObjects(map);
return modelAndView;
}
}
and this is my property snippet for file uploading,
# MULTIPART (MultipartProperties)
multipart.enabled=true
multipart.max-file-size=5Mb
multipart.max-request-size=10Mb
If I tried to upload a file a bit larger than 5M, I will get the result like below under Postman, (the file size is 5208k)
enter image description here
and if I tried to upload a file between 5M and 10M, I will get this error, (the file size is 9748k)
enter image description here
I debugged into the controller and found that the resolveException method executed twice in a single upload.
Does anybody give me some tip?
The latest code list here, and I still got the same result,
#RestController
#ControllerAdvice
public class FileUploadController {
private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class);
private static final String UPLOAD_PATH = "upload";
#RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = "multipart/form-data", produces = "application/json;charset=UTF-8")
public HttpEntity<?> upload(final MultipartFile file) {
try {
final Result<String> result = new Result<>();
if (file == null || file.isEmpty()) {
result.setSuccess(false);
result.setMessage("上传的文件为空");
return new ResponseEntity<Result<?>>(result, HttpStatus.OK);
}
final File outputFile = new File(UPLOAD_PATH, UUID.randomUUID().toString());
FileUtils.writeByteArrayToFile(outputFile, file.getBytes());
result.setSuccess(true);
result.setMessage(outputFile.toString());
return new ResponseEntity<Result<?>>(result, HttpStatus.OK);
} catch (final Exception ex) {
LOGGER.error(ex.getMessage(), ex);
return ExceptionResultBuilder.build(ex);
}
}
#ExceptionHandler(MultipartException.class)
public HttpEntity<?> multipartExceptionHandler(final MultipartException exception) {
LOGGER.error(exception.getMessage(), exception);
try {
final Result<String> result = new Result<>();
result.setSuccess(false);
final Throwable rootCause = ((MultipartException) exception).getRootCause();
if (rootCause instanceof SizeLimitExceededException) {
result.setMessage("请求过大");
} else if (rootCause instanceof FileSizeLimitExceededException) {
result.setMessage("文件过大");
} else {
result.setMessage("未知错误");
}
return new ResponseEntity<Result<?>>(result, HttpStatus.OK);
} catch (final Exception ex) {
LOGGER.error(ex.getMessage(), ex);
return ExceptionResultBuilder.build(ex);
}
}
}
I just go the same error and fix it by add the flowing code to my controller, good luck
#ExceptionHandler({ MultipartException.class, FileSizeLimitExceededException.class,
SizeLimitExceededException.class })
public ResponseEntity<Attachment> handleUploadrException(HttpServletRequest request, Throwable ex) {
Attachment result = new Attachment();
result.setDescription(ex.getMessage());
HttpStatus status = getStatus(request);
return new ResponseEntity<Attachment>(result, status);
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
}

SMACK API In Band registration fails with forbidden error

I am using SMACK API's AccountManager class but failed to successfully create a new account. supportsAccountCreation() returns true.
The createAccount method fails with the following error.
D/SMACK: SENT (0): <iq to='xmpp.jp' id='e740L-48' type='set'><query xmlns='jabber:iq:register'><username>MY_NEW_USER</username><password>**********************</password></query></iq>
D/SMACK: RECV (0): <iq from='xmpp.jp' id='e740L-48' type='error'><query xmlns='jabber:iq:register'><username>MY_NEW_USER</username><password>*****************</password></query><error code='403' type='auth'><forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error></iq>
W/System.err: org.jivesoftware.smack.XMPPException$XMPPErrorException: XMPPError: forbidden - auth
W/System.err: at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:232)
W/System.err: at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:213)
W/System.err: at org.jivesoftware.smackx.iqregister.AccountManager.createAccount(AccountManager.java:272)
W/System.err: at org.jivesoftware.smackx.iqregister.AccountManager.createAccount(AccountManager.java:244)
..
D/SMACK: SENT (0): <auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='SCRAM-SHA-1'>*****************************************</auth>
D/SMACK: RECV (0): <failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><not-authorized/></failure>
UPDATE: Code added here
API v4.1.5
private void initialiseConnection() {
Log.d("xmpp", "Initialising connection");
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(getServer());
config.setHost(getServer());
config.setPort(getPort());
config.setDebuggerEnabled(true);
config.setSendPresence(true);
XMPPTCPConnection.setUseStreamManagementResumptionDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
connection = new XMPPTCPConnection(config.build());
connection.addConnectionListener(new XMPPConnectionStateHandler(this));
connection.addConnectionListener(new XMPPAccountLoginHandler(this));
connection.addConnectionListener(new XMPPOfflineMessageHandler(this));
connection.addConnectionListener(new XMPPPingMessageHandler(this));
connection.addConnectionListener(new XMPPReconnectionHandler(this));
connection.addConnectionListener(new XMPPPresenceHandler(this));
connection.addConnectionListener(new XMPPDeliveryReceiptHandler(this));
}
public void connect(final String caller) {
if (ConnectionManagerHelper.hasDataConnection(context)){
Log.d(TAG, "Data connection fine");
} else {
Log.d(TAG, "Data connection not avaiable");
}
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected synchronized Boolean doInBackground(Void... arg0) {
if (connection.isConnected()) return false;
isconnecting = true;
Log.d("Connect() Function", caller + "=>connecting....");
try {
connection.connect();
connected = true;
notifyConnectionEstablishedEvent();
} catch (IOException e) {
Log.e(TAG, "(" + caller + ")" + " IOException: " + e.getMessage());
notifyConnectionFailureEvent();
} catch (final SmackException e) {
Log.e(TAG, "(" + caller + ")" + " SMACKException: " + e.getMessage());
notifyConnectionFailureEvent();
} catch (final XMPPException e) {
Log.e(TAG, "(" + caller + ")" + " XMPPException: " + e.getMessage());
notifyConnectionFailureEvent();
}
return isconnecting = false;
}
};
connectionThread.execute();
}
public void login() {
try {
connection.addAsyncStanzaListener(new StanzaListener() {
#Override
public void processPacket(Stanza packet) throws NotConnectedException {
Log.d(TAG, packet.toXML().toString());
notifyMessageStatusReceivedEvent(packet);
}
}, new StanzaFilter() {
#Override
public boolean accept(Stanza stanza) {
return true;
}
});
Log.d(TAG, "Attempting to login as " + loginUser);
connection.login(loginUser, passwordUser);
notifyConnectionConnectedEvent();
} catch (SmackException.AlreadyLoggedInException e){
Log.d(TAG, "Already logged on to chat server");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
//if first login failed, try to create an account and then login
Log.d(TAG, "Login failed. Trying to create a new account.");
register();
}
}
public void register(){
Log.d(TAG, "Attempting to register");
try {
AccountManager accountManager = AccountManager.getInstance(connection);
if (accountManager.supportsAccountCreation()){
Log.d(TAG, "Server supports remote registration");
accountManager.sensitiveOperationOverInsecureConnection(true);
Log.d(TAG, "Sending registration request");
HashMap<String, String> attributes = new HashMap<>();
attributes.put("email", "test#gmail.com");
accountManager.createAccount(loginUser, passwordUser, attributes);
} else {
Log.w(TAG, "Server does not support remote registrations");
}
} catch (XMPPException | SmackException e) {
e.printStackTrace();
}
}
I have spent 3 days already googl-ing and stackoverflow-ing.
Has someone seen and fixed this already?
You have to set access rules for registering new user. I have attached here the complete access rules. You can add this by clicking raw in access rules.
[{access,announce,[{allow,[{acl,admin}]}]},
{access,c2s,[{deny,[{acl,blocked}]},{allow,[all]}]},
{access,c2s_shaper,[{none,[{acl,admin}]},{normal,[all]}]},
{access,configure,[{allow,[{acl,admin}]}]},
{access,local,[{allow,[{acl,local}]}]},
{access,max_user_offline_messages,[{5000,[{acl,admin}]},{100,[all]}]},
{access,max_user_sessions,[{10,[all]}]},
{access,mod_register,[{access_from,register_from},{access,register}]},
{access,register,[{allow,[{acl,local}]}]},
{access,muc_create,[{allow,[{acl,local}]}]},
{access,pubsub_createnode,[{allow,[{acl,local}]}]},
{access,register,[{allow,[all]}]},
{access,register_from,[{allow,[all]}]},
{access,s2s_shaper,[{fast,[all]}]},
{access,trusted_network,[{allow,[{acl,loopback}]}]}]
The below code worked for me,
AccountManager accountManager = AccountManager.getInstance(connection);
try {
if (accountManager.supportsAccountCreation()) {
accountManager.sensitiveOperationOverInsecureConnection(true);
accountManager.createAccount("name", "password");
}
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}

Writing a mock function for testing a login application

I am making the authentication of my android application, I want to send the entered password & email in json format then my web service is going to test if they are correct then it will return the result in json format also.
But before doing this, I want to make a mock function that replace my webservice and do this just to test before .
Here is the code
After making the validation of interface(Email & password are valid )
mock class
if(fault==false)
//new AttemptLogin().execute();
new GetUser().execute();
My class GetUser is here (the mock class that will replace my web service )
private class GetUser extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String e2=email.getText().toString();
String p2=password.getText().toString();
if (e2 != null && p2!=null) {
try {
JSONObject jsonObj1 = new JSONObject(e2);
JSONObject jsonObj2 =new JSONObject(p2);
UserEmail=jsonObj1.getJSONObject(TAG_Email);
UserPassword=jsonObj2.getJSONObject(TAG_Password);
Toast.makeText(getApplicationContext(),"hi",
Toast.LENGTH_LONG).show();
String c=checkLogin(UserEmail, UserPassword);
Toast.makeText(getApplicationContext(),c,
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(String result) {
// dismiss the dialog once product deleted
if (pDialog.isShowing())
pDialog.dismiss();
if (result != null){
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
}
And this is the method checkLogin that check if the user has logged with the right email & password .
protected String checkLogin(JSONObject UserEmail,JSONObject UserPassword) {
String e ;
String p;
String r="";
try {
e= UserEmail.getString(TAG_Email);
p = UserPassword.getString(TAG_Password);
if (e.equals("exemple.android#yahoo.fr") &&
p.equals("123456")) {
Toast.makeText(getApplicationContext(), "Hello imene!",
Toast.LENGTH_SHORT).show();
r="ok";
} else {
Toast.makeText(getApplicationContext(), "Seems like you 're not imene!",
Toast.LENGTH_LONG).show();
numberOfRemainingLoginAttempts--;
Toast.makeText(getApplicationContext(), "number of Remaining login Attemts ="+numberOfRemainingLoginAttempts,
Toast.LENGTH_LONG).show();
if (numberOfRemainingLoginAttempts == 0) {
validate.setEnabled(false);
Toast.makeText(getApplicationContext(), "Login Locked!",
Toast.LENGTH_LONG).show();
r="ko";
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return r;
}`
But ,i don't have any result .Can any one tell me where is the problem in my code .

JMS message consumption isn't happening outside of a bean

I'm running through a Glassfish web process and I need a non-container managed class (EJBUserManager) to be able to receive messages from a MessageDrivenBean. The class has the javax.jms.Queues and connection factories and I can write to the Queues. The queue sends to a MessageDrivenBean (AccountValidatorBean) that receives the code correctly, and then writes back a message. But the EJBUserManager attempts to read from the queue and never receives the message.
#Override
public boolean doesExist(String username) throws FtpException {
LOGGER.finer(String.format("Query if username %s exists", username));
QueueConnection queueConnection = null;
boolean doesExist = false;
try {
queueConnection = connectionFactory.createQueueConnection();
final UserManagerMessage userManagerMessage =
new UserManagerMessage(UserManagerQueryCommands.VALIDATE_USER, username);
final Session session = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final ObjectMessage objectMessage = session.createObjectMessage(userManagerMessage);
session.createProducer(accountValidatorQueue).send(objectMessage);
session.close();
queueConnection.close();
queueConnection = connectionFactory.createQueueConnection();
final QueueSession queueSession =
queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
LOGGER.finest(String.format("Right before doesExist receive for username %s", username));
final Message firstAttemptMessage = queueSession.createConsumer(userManagerQueue).receive(3000);
final Message message = firstAttemptMessage != null ?
firstAttemptMessage : queueSession.createConsumer(userManagerQueue).receiveNoWait();
LOGGER.finest(String.format("Right after doesExist receive for username %s", username));
LOGGER.finest(String.format("Is the message null: %b", message != null));
if (message != null && message instanceof StreamMessage) {
final StreamMessage streamMessage = (StreamMessage) message;
doesExist = streamMessage.readBoolean();
}
} catch (JMSException e) {
e.printStackTrace();
} finally {
if (queueConnection != null) {
try {
queueConnection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
return doesExist;
}
The above is the code from the EJBUserManager. Now, it can send to the accountValidatorQueue. It just never receives from the userManagerQueue
Here's the code for the AccountValidatorBean
private void validateUser(final String username) {
QueueConnection queueConnection = null;
final String doctype = doctypeLookupDAO.getDocumentTypeForUsername(username);
LOGGER.finest(String.format("Doctype %s for username %s", doctype, username));
try {
queueConnection = queueConnectionFactory.createQueueConnection();
final Session session = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//final StreamMessage message = session.createStreamMessage();
//message.clearBody();
//message.writeBoolean(doctype != null);
//message.reset();
final ObjectMessage message = session.createObjectMessage(Boolean.valueOf(doctype != null));
final MessageProducer messageProducer =
session.createProducer(userManagerQueue);
LOGGER.finest(String.format("Queue name %s of producing queue", userManagerQueue.getQueueName()));
messageProducer.send(message);
LOGGER.finest(String.format("Sending user validate message for user %s", username));
messageProducer.close();
session.close();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if (queueConnection != null) {
try {
queueConnection.close();
} catch (JMSException e1) {
e1.printStackTrace();
}
}
}
}
Fixed. I needed to call QueueConnection.start() to consume messages from the queue.