Simple way to send message to Azure Event Hub - second approach - java

My first approach was to use the com.microsoft.azure:azure-eventhubs:3.2.0 dependency but I had the following problem: Client hangs when calling Azure Event Hub and facing connection error
So my 2nd approach can be
either to use another dependency (I need to use OAuth2 too) -> unfortunately I haven't found any
or don't use a dependency but code the message sending myself -> it might be a big task
Could you please recommend me library that supports OAuth2?
Or a sample code which supports message sending to Event Hub over AMQP with OAuth2?
Or a 3rd approach ...?
Thanks,
V.

Regarding your hang issue, I posted a new answer in the original thread Client hangs when calling Azure Event Hub and facing connection error. That should fix your issue.
Now coming back to this question, primarily you should follow the latest tutorial (uses Event Hub v5 sdk using Producer/Consumer pattern).
import com.azure.messaging.eventhubs.*;
public class Sender {
public static void main(String[] args) {
final String connectionString = "EVENT HUBS NAMESPACE CONNECTION STRING";
final String eventHubName = "EVENT HUB NAME";
// create a producer using the namespace connection string and event hub name
EventHubProducerClient producer = new EventHubClientBuilder()
.connectionString(connectionString, eventHubName)
.buildProducerClient();
// prepare a batch of events to send to the event hub
EventDataBatch batch = producer.createBatch();
batch.tryAdd(new EventData("First event"));
batch.tryAdd(new EventData("Second event"));
batch.tryAdd(new EventData("Third event"));
batch.tryAdd(new EventData("Fourth event"));
batch.tryAdd(new EventData("Fifth event"));
// send the batch of events to the event hub
producer.send(batch);
// close the producer
producer.close();
}
}
Regarding the question on OAuth2, it is very much possible to leverage AAD authentication approach instead of Shared Access Signature (the default connection string approach). You can follow this tutorial for Managed Identity scenario OR this tutorial for custom AAD application based auth.
Regarding the recommendation on OAuth2 library, the first party choice in the Azure world would be MSAL for seamless integration and support.
Regarding the question on writing the whole thing by custom code, while it's technically possible, but honestly it's super impractical to invest on this mammoth task due to following reasons:
Why to reinvent the wheel?
It will increase your maintenance headache for a hell lot of custom code which does only technical wiring, but hardly adds any value to the business.
You would be pretty much on your own to figure out any issue or future compatibility.
Adding all the low level AMQP and OAuth handling in your code would add unnecessary burden to your team to master those.
..and most importantly it would cost Money and Time :)
Using standard libraries not only saves you from lot of efforts and money, but ensures reusability, and support from both the creator and communities.

Related

How can I get the enqueue and dequeue count for an ActiveMQ queue WITHIN my Java Spring app?

I have been scouring the internet for documentation on this and it's unbelievable how difficult it is to find. My goal is to create a REST endpoint where I can return queue details such as enqueue, dequeue, etc. counts for a custom dashboard I am making.
I keep seeing documentation such as this, this, and this, but I can't seem to figure out how to get these details in my actual program. I have gotten about as far as using the JMX GUI, but that really is not the direction I need to be going. Can anyone help me figure out how to get simple connection to a broker that will return these details? I really have tried to research this, but I have not been able to figure out a way to incorporate this information to my application in any meaningful away.
The way to monitor the broker is via the broker JMX endpionts and the management beans it exposes. Other means would be through the Jolokia REST API that exposes those same MBeans. One article showing how to use the Jolokia bits is here.
A brief example of using JMX with ActiveMQ is below.
// connection
String url = "service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi";
JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(url));
MBeanServerConnection connection = connector.getMBeanServerConnection();
// get queue size
ObjectName nameConsumers = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=myqueue");
DestinationViewMBean mbView = MBeanServerInvocationHandler.newProxyInstance(connection, nameConsumers, DestinationViewMBean.class, true);
long queueSize = mbView.getQueueSize();

How check my device is connected (IOTCore - GCP) [duplicate]

Does anybody know of an easy way to trigger an event when a device on Google Core IoT goes offline? Before I switched to Google's IoT implementation, this was very easily handled by triggering an event when MQTT disconnects, but it seems Google has no easy way of doing this.
Does anybody know if there is something planned for this?
Who's back do I need to scratch to get them to see that something like this is a basic requirement for IoT device management!
Other platforms like AWS and Microsoft already have this implemented (or some way to handle it easily):
https://docs.aws.amazon.com/iot/latest/developerguide/life-cycle-events.html
Device connectivity(online/offline)status with the Auzure iot hub
I wish I had known this before writing all my code and implementing my setup using Google's IoT platform, I guess that's my fault for assuming something so simple and that should be standard for IoT devices would be available.
How are you going to compete with other IoT providers if you can't even provide basic offline/online events?!
My reply in this SO question shows how I had to write 100+ lines of code just to create a firebase function to check if a device is online (but that still doesn't handle offline events, and is just a hack for something that should be native to ANY IoT service provider!):
https://stackoverflow.com/a/54609628/378506
I'm hoping someone else has figured out a way to do this, as i've spent numerous days searching SO, Google, Google Core IoT Documentation, and still have not found anything.
Even if MQTT Last Will was supported we could make that work, but even that IS NOT SUPPORTED by Google (https://cloud.google.com/iot/docs/requirements) ... come on guys!
Your cloud project does have access to the individual MQTT connect/disconnect events, but currently they only show up in the Stackdriver logs. Within the cloud console, you can create an exporter that will publish these events to a Pub/Sub topic:
Visit the Stackdriver Logs in the
Cloud Console.
Enter the following advanced filter:
resource.type="cloudiot_device"
jsonPayload.eventType="DISCONNECT" OR "CONNECT"
Click CREATE EXPORT
Enter a value for Sink Name
Select Cloud Pub/Sub for Sink Service
Create a new Cloud Pub/Sub topic as the Sink Destination
The exporter publishes the full LogEntry, which you can then consume from a cloud function subscribed to the same Pub/Sub topic:
export const checkDeviceOnline = functions.pubsub.topic('online-state').onPublish(async (message) => {
const logEntry = JSON.parse(Buffer.from(message.data, 'base64').toString());
const deviceId = logEntry.labels.device_id;
let online;
switch (logEntry.jsonPayload.eventType) {
case 'CONNECT':
online = true;
break;
case 'DISCONNECT':
online = false;
break;
default:
throw new Error('Invalid message type');
}
// ...write updated state to Firebase...
});
Note that in cases of connectivity loss, the time lag between the device being unreachable and an actual DISCONNECT event could be as long the MQTT keep-alive interval. If you need an immediate check on whether a device is reachable, you can send a command to that device.
The best solution i think is that
We need 3 things
cloud sheduler ,
and 2 cloud functions
The first function will be the #devunwired answer but instant of
// ...write updated state to Firebase... schedule a second function to trigger in 2-3 min (let device to recconect)
the seccond function will send a command to device
if the device resposne to command
if stored status is connected dont do nothing
else if the stored status is disconnected then update the status to connected and do what ever you want maybe email
else
if stored status is disconnected dont do nothing
if stored status is connected change the status alert by email or something

DocuSign AutoResponded RecipientEvent

I am building an envelope based webhook to receive status updates from DocuSign, rather than my current "polling" based method. I have the below code to create the RecipientEvent
RecipientEvent autoRespondedRecEvent = new RecipientEvent();
autoRespondedRecEvent.setRecipientEventStatusCode("AutoResponded");
recipientEvents.add(autoRespondedRecEvent);
I have similar RecipientEvents for Sent, Delivered, Completed, Declined, and AuthenticationFailed; however, all of these events work as intended, other than the 'AutoResponded' one.
Again, I am not using the account-level webhook, but the envelope based setup as have a fairly complex development/test environment. I have read another question on SO where the solution was a configuration setting
Return Recipient Auto Responded Status via Connect/Api
However, this solution does not apply in my case, as I'm not using an account-level webhook.
That's a back-end setting that should still apply through envelope-level webhooks. I'd recommend opening a support case to have Return Recipient Auto Responded Status in Connect/API enabled for your account.
I'd recommend providing both your Demo and Production account IDs when you do so.

Java Google datastore async calls

I do not want to block threads in my application and so I am wondering are calls to the the Google Datastore async? For example the docs show something like this to retrieve an entity:
// Key employeeKey = ...;
LookupRequest request = LookupRequest.newBuilder().addKey(employeeKey).build();
LookupResponse response = datastore.lookup(request);
if (response.getMissingCount() == 1) {
throw new RuntimeException("entity not found");
}
Entity employee = response.getFound(0).getEntity();
This does not look like an async call to me, so it is possible to make aysnc calls to the database in Java? I noticed App engine has some libraries for async calls in its Java API, but I am not using appengine, I will be calling the datastore from my own instances. As well, if there is an async library can I test it on my local server (for example app engine's async library I could not find a way to set it up to use my local server for example I this library can't get my environment variables).
In your shoes, I'd give a try to Spotify's open-source Asynchronous Google Datastore Client -- I have not personally tried it, but it appears to meet all of your requirements, including being able to test on your local server. Please give it a try and let us all know how well it meets your needs, so we can all benefit and learn -- thanks!

How to use Javapns to Support Apple's Enhanced Notification Format

Greetings,
I am creating a Java based server to create push notifications for Apple's iOS APNs service. I have found Javapns on google code which seems to provide a simple basic framework to communicate with APNs, and which seems to be fairly wide used.
http://code.google.com/p/javapns/
However, reading Apple's docs, there is an "enhanced format" for notifications which supports "expiry" i.e. setting a time (well, in seconds) for a notification to expire if it hasn't yet been delivered. I do not see any way to set this using Javapns, and I am unsure how the APNs service handles expiry of notifications if you do not explicitly set it. So,
Does anyone know how to support the enhanced notification format of APNs specifically how to set the expiry?
Does anyone know how Apple handles notification expiry if it isn't explicitly set?
Does anyone have any suggestions that don't require me to start from scratch, as the server is currently functional as is?
Thanks in advance.
Andrew
I have recently made substantial contributions to the JavaPNS project, which lead to the release of JavaPNS 2.0 a few days ago. That version provides full support for the enhanced notification format, including the ability to set your own expiry.
Sylvain
Nice that you found the java library... to bad you didn't read the docs there.
I'll post some of the highlights below:
The existing code uses the 'Simple notification format' which does not return an error EVER.
See docs at:
http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingWIthAPS/CommunicatingWIthAPS.html
I've tried updating to the 'Enhanced notification format' which is supposed to return an error, but I'm unable to get any errors back from the APNS. (also in the link above)
With the Enhanced format, the connection isn't being dropped immediately after sending data, but I'm not getting anything back from my socket.getInputSocket.read() call.
This issue will have to be tabled until I have more time to troubleshoot.
(Someone else commented)
Thanks a lot for looking into it.
I got the same result as yours. Maybe it has something to do with Apple Gateway.
So... you could:
1) Build your own
2) Help improve the existing library
3) Try another library like: https://github.com/notnoop/java-apns
4) Do nothing
Enhanced ios push here.
To send a notification, you can do it in three steps:
Setup the connection
ApnsService service =
APNS.newService()
.withCert("/path/to/certificate.p12", "MyCertPassword")
.withSandboxDestination()
.build();
Create and send the message
String payload = APNS.newPayload().alertBody("Can't be simpler than this!").build();
String token = "fedfbcfb....";
service.push(token, payload);
To query the feedback service for inactive devices:
Map<String, Date> inactiveDevices = service.getInactiveDevices();
for (String deviceToken : inactiveDevices.keySet()) {
Date inactiveAsOf = inactiveDevices.get(deviceToken);
...
}

Categories