Where can one get the user name for a connection in the SDK? The only place that I have found is on the ConnectPacket from ConnectionStartInput. Is there any way to get it from say, DisconnectEventInput or SessionInformation?
Hi @jlenthe,
as you already said, you can only get the username via the ConnectPacket. If you need the username somewhere else then you can store/retrieve the username in the ConnectionAttributeStore.
You can retrieve the store via the ClientBasedInput (which is part of the input of all methods with client context), here a simple example, were we store the username in onMqttConnectionStart
and retrieve the username in onDisconnect
:
@Override
public void extensionStart(final ExtensionStartInput input, final ExtensionStartOutput output) {
Services.eventRegistry().setClientLifecycleEventListener(prov -> new ClientLifecycleEventListener() {
@Override
public void onMqttConnectionStart(final ConnectionStartInput connectionStartInput) {
final ConnectionAttributeStore connectionAttributeStore = connectionStartInput.getConnectionInformation().getConnectionAttributeStore();
connectionStartInput.getConnectPacket().getUserName().ifPresent(username ->
connectionAttributeStore.put("username", ByteBuffer.wrap(username.getBytes(UTF_8))));
}
@Override
public void onAuthenticationSuccessful(final AuthenticationSuccessfulInput authenticationSuccessfulInput) {
//noop
}
@Override
public void onDisconnect(final DisconnectEventInput disconnectEventInput) {
final ConnectionAttributeStore connectionAttributeStore = disconnectEventInput.getConnectionInformation().getConnectionAttributeStore();
final Optional<@Immutable ByteBuffer> usernameBytes = connectionAttributeStore.get("username");
final String username;
if (usernameBytes.isPresent()) {
username = UTF_8.decode(usernameBytes.get()).toString();
}
//do something with username
}
});
}
Hope this helps!
Greetings
Michael from the HiveMQ team
Thank you! I appreciate you confirming what I suspected and giving me an example of how to use the connection attribute store.
No problem! A little addition, as the name already suggest, the ConnectionAttributeStore only holds the information as long as the client is connected. If the client disconnect all information in the ConnectionAttributeStore is erased.