Send data to another server when it's updated - java

I am writing a service which would store picture associated with registered email. So, other domains would have a possibility to get image of the user by email. The main goal is not to upload it each time as nowadays we have to register almost everywhere and that process is quite annoying.
My application is written on Java and I am using REST API.
For example, user's account information is available by login:
#RequestMapping(value = "/get/{login}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<User> getByEmail(#PathVariable String login) {
User user = userDao.getUserByLogin(login);
return Optional.ofNullable(user)
.map(result -> new ResponseEntity<>(
result, HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
And now, what i want is to send just updated data to the domains which gonna use my service. How could I figure that out? I think I could ask "domain" to provide some information in order to use my service (some king of registration), but what exactly should I ask for to be able to send data udpdates?
In my thoughts they should also provide some REST path where I could send some kind of request that something has changed.
Any help would be appreciated a lot, thanks.

This is essentially a pub-sub model . You publish some information , on various defined events , to whoever has subscribed to it . Look at this as a subset of state syncronisation of the user information across various endpoints.
In your case , the 'domains' you are referring to would be subscribers of your service and the events could be 'itemAdded' , 'itemAdded' etc. You would want to 'push' out the updates ( or whole info) to the subscribers when the event they have subscribed for occurs , instead of them trying to pull this at some frequency ( that would be a lot of waste calls to your server - you dont want that ! )
There are various solutions available that could achieve this . The one I am going to point you to is called Twilio Sync . This would obviously mean that the 'domains' would have to do some changes at their end to subscribe and consume the updates , but I dont see how else could they be regularly updated if they want information pushed.

Send last update date to the endpoint from the domain which
use it. Then check which data was updated after that date and return
appropriate response.
Talking about image, you can always return URL for download but add last update field. The service which use REST service will determine to download it or not.
Also you may need event driven messaging, publish–subscribe pattern (https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern). Related threads:
How would I create an asynchronous notification system using RESTful web services?
Event Based interaction style in REST
Firebase for mobile apps: https://firebase.google.com/docs/notifications/

Related

Android/Java: how to send notifications to user, even when app is not "actively" being used?

I want to be able to send a notification to a user IF something changes.
For example, my application is crime-related. So users can submit reports of crimes that have happened in their neighborhoods.
When a new crime is reported, I want to be able to send ALL users in that specific neighbourhood a notification, even if they are not actively using the app.
How can this be done? I'm quite new at this but to my understanding services like Firebase Messaging require you to type out a message manually and select users to send the message to manually. I'm wondering if there's a way this can be done without someone having to manually do work?
Similar to how snapchat/instagram and stuff will send you notifications that someone has sent you a message even when you are not using your phone.
In my case, I just want the same standard notification "New crime in your area" to be displayed...
How can I do this? (Currently for notifications I'm just using Notification Channels), thank you so much!
You can easily do this using Parse Server through FCM integration.
First, you need to setup your Android app to be able to receive push notifications
Just follow this Quickstart: https://docs.parseplatform.org/parse-server/guide/#push-notifications-quick-start
Second, you need to create a cloud code function
I suggest you to create a cloud code function that will receive the neighborhood as parameter, will query for the user installations in that neighborhood and send the push notification to all of them.
It would be something like this:
Parse.Cloud.define('notifyCrime', async req => {
const query = new Parse.Query(Parse.Installation);
query.equalTo('neighborhood', req.params.neighborhood); // I'm supposing you have a field called neighborhood in your installation class - if not, you can save this field there when the user sign up
await Parse.Push.send({
where: query,
data: {
alert: 'There is a crime in your neighborhood'
},
useMasterKey: true
});
});
Reference: https://docs.parseplatform.org/js/guide/#sending-pushes-to-queries
Third, you need to call the cloud function from your Android app
Once some user has reported a crime, you can call the cloud code function that you created in step 2 to notify all other users in the same neighborhood.
It would be something like this:
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("neighborhood", "The neighborhood goes here");
ParseCloud.callFunctionInBackground("notifyCrime", params, new FunctionCallback<Object>() {
void done(Object response, ParseException e) {
if (e == null) {
// The users were successfully notified
}
}
});
Reference: https://docs.parseplatform.org/cloudcode/guide/#cloud-functions
"my understanding services like Firebase Messaging require you to type out a message manually and select users to send the message to manually".
This is not completely true. There is a method name Firebase Topic Messaging, that lets you send notifications to specific user segments only. You have to register from the app for that topic and then, you can send customized message to your user groups based on topics they subscribed to.

How to process each product one by one with incremental progress update using Spring reactive?

I need help on Spring Reactive where a rest call posts list of Json objects and spring boot server should send the processing events one by one.
Let me explain in brief with an example.
Let us take there are 20 products in the Front-end UI, user selects all the products to be processed.
Each product processing takes minimum 1 min in the server side. Whenever each product is processed, server should send json message structure as
event to the Front-end UI so that user will be able to see incremental progress of each product processing in the server.
In the UI , it should look like this.
Product 1 processed successfully
Product 2 processed successfully
Product 3 failed
like this.....
In the server side, the java code should be like this. Please suggest how to achieve using Spring Reactive.
public Flux<ProdModel> createAllCGs(List<Product> prodList) {
for(Product p : prodList) {
//Process here ...
}
//use Spring Reactor Flux
//return Flux type object in the form of Json structure event not as Text Stream event.
}
I know there are workarounds to achieve it using traditional polling mechanism or sending the product one by one.
My question is more on Spring Reactive side where the rest call sends a bunch of products to be processed one by one by providing corresponding
response in the json format to the UI side.
I do not know whether it is possible or not. If you think it is not possible using Spring Reactive, that is also fine for me so that I can communicate to my architect who has suggested this.
I struggled a bit to find out the answer,I an also new to Spring Reactive. I hope this answer will help to other.
I provide below the code snippet.
public Flux<ProdModel> createAllCGs(List<Product> prodList) {
return Flux.fromIterable(prodList)
.map(
prodModel -> {
System.out.println("Input Data VM ::: " + prodModel);
return getProdModel(reviewModel);
})
.delayElements(Duration.ofSeconds(3));
}
private getProdModel getProdModel(ProdModel prodModel) {
logger.debug("Time Now: {}", LocalDate.now());
ProdModel cgModel = new CGModel();
cgModel.setCgName("some Name");
cgModel.setMessage("some meaningful message");
cgModel.setTimestamp(LocalDateTime.now().toString());
return cgModel;
}
If you create a simple GET type rest end point and use the above method, you can see the output one by one after 3 seconds in the browser.

Paypal subscription integration full cycle missing in documentation?

I already have an implemented CMS system where the user creates the subscription plans.
I want to integrate my CMS server with Paypal so when the user creates a plan it will be created on Paypal servers.
I can see how to do that in https://developer.paypal.com/docs/subscriptions/integrate/
But the problem is there is no documentation for the front-end side for the subscription step ! How should i redirect the customer to Paypal to login, and how will i receive the data to send it to my server ?
Note : Since i want my user to create plans only on my CMS, there is no easier way to integrate with paypal than this : https://developer.paypal.com/docs/subscriptions/integrate/ .. right?
i don't want to use Smart Buttons so the only option i have is to integrate with APIs.. if there is any easier way please tell me.
This is a bit hidden.
When you create a subscription, its status will be set to APPROVAL_PENDING. Look for the "rel": "approve" link in the response (in links). The URL will look something like this:
https://www.paypal.com/webapps/billing/subscriptions?ba_token=xyz
This is the URL you need to redirect the customer's browser to. Once they click on "Subscribe" to approve it, PayPal will redirect their browser to the return_url value you set when you created the subscription.
PayPal adds 3 extra parameters to that return URL: subscription_id (self-explanatory), ba_token (the approval token), and token (???). At that point, you can get the subscription details from PayPal, and its status should now be "ACTIVE".
Now I just need to figure out why next_billing_time is set in the past, and why I'm not receiving the PAYMENT_SALE webhooks :)
Hope this answers your question.

How can I access a mirror service with userid?

I want to receive XMPP message with app engine, and then use a look up table to find the corresponding glass's userid and push timeline cards. I saw the service was created in OAuth. Do I need to create a new service each time? Or I can get the service with userid? Is there any references on service?
Thanks
This is the code I'm using. Currently I'm creating a new mirror service each time I got a message. Will that cause any trouble or there is a better way to do that? Is there and reference to "util.create_service"?
class XmppHandler(xmpp_handlers.CommandHandler):
def push_command(self, message=None):
if message.arg:
id=XMPP_addr_access.get_id_from_addr(bare_jid(message.sender))
if id is not None:
creds=StorageByKeyName(Credentials, id, 'credentials').get()
mirror_service = util.create_service('mirror', 'v1', creds)
body = {'notification': {'level': 'DEFAULT'}}
body['text'] = message.arg
mirror_service.timeline().insert(body=body).execute()
In my Glassware, notification responses (what I believe you are calling a service) run similar code to what you have, I generate a new Credential using the java helper method AuthUtil.getCredential(String userId) every time I need to make another Mirror API request based on an incoming notification in App Engine.
This credential is used in a MirrorClient object that uses the same userId and does the insert back into the timeline.
I get the userId by looking it up in a persisted store referenced by the userToken that the notification provides.

Scribe - multiple callback simultaneously

I am making a module for a server software that is allowing support for facebook.
The problem is with the callback URL. If one client start the authorization proccess, then another client starts the proccess at the same time, or before the first user finish. How could I check what user finished first?
I need a way to check what client's callback I'm getting. One solution would be to lock other from register until the first one has finished, but I don't want to do that. Is there another way? I have thought about including ?client=clientid at the end of the callback, but I heard facebook only allows the exact url specified in the app on facebook.
UPDATE
It didn't work to add client="clientid" to the callback. Any other ideas?
After some more searchig I figured facebook will allow a parameter: state. (thanks to #jacob https://stackoverflow.com/a/6470835/1104307)
So I just did ?state=clientId.
For anyone using scribe the code is this:
service.getAuthorizationUrl(null) + "&state=" + clientId;
I think there is no problem on adding and GET parameter like client=clientID. Facebook will redirect you to the URL you have specified and using the REQUEST parameters you can check who completed the request. The problem exist if you have specified URL as http://yoursite.com and pass redirect to http://some-sub-domain.yoursite.com or entirely different location.
if you are using the server-side flow then the oauth 2 flow will be:
redirect user to facebook
facebook then rediects the user to your specified callback
your server uses something like curl to get the access token
your server does some more curl to get maybe more user data or update the user's data
my recommendation would be to set a session cookie in step 1 and simultaneously store this session id on your server. then the session cookie will automatically be sent to the callback url in step 2 and you can identify the session in the database this way.
this will work for all service providers (google, twitter, linkedin, etc) and is the preferred way of maintaining session continuity.

Categories