How to create a SOAP request in EWS? - soap

I've got such kind of class with required login, password, url and domain:
class Service
{
public ExchangeService service;
public void Connect()
{
const string exchangeUser = "login";
const string exchangePassword = "password";
const string exchangeUri = "url";
service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
service.UseDefaultCredentials = true;
service.Credentials = new WebCredentials(exchangeUser, exchangePassword, "domain");
service.Url = new Uri(exchangeUri);
}
}
And I need to add such method as CreateAppointment()
public void CreateAppointment()
{
Appointment appointment = new Appointment(service);
appointment.Subject = "Team building exercise";
appointment.Body = "Let's learn to really work as a team and then have lunch!";
appointment.Start = DateTime.Now.AddHours(2);
appointment.End = appointment.Start.AddHours(4);
appointment.Location = "Some city";
appointment.RequiredAttendees.Add("somebody#something.com");
appointment.ReminderMinutesBeforeStart = 30;
appointment.Save(SendInvitationsMode.SendToNone);
}
Save() method doesn't work because of some reasons for creating service and appointment objects. So I need to rewrite this method using xml request. And I've got an example of SOAP request from msdn https://msdn.microsoft.com/en-us/library/office/dd633661(v=exchg.80).aspx
How could I insert the SOAP request instead of CreateAppointment() method? I've got no idea what to do with xml code to make it work as CreateAppointment() method.

Related

I am not able to call a #Future method

I understand that I cannot directly call a future method from a batch class. But from many other answers, I can see that it is possible to do so by creating a helper class and calling the future method there. But it is not working for me. Please check my code below.
Also, I have tried to do it with the queueable class as suggested in this link, but it is not working for me. The error was " Callout not allowed from this future method. Please enable callout by annotating the future method. eg: #Future(callout=true)"
But I am more interested in the first and simpler way to do this.
public class OrdersItemsHelper {
static Document tDoc;
static blob csvBlob;
//prepare csv file to send
public static void CreateCsvFile(List<Order_Line_Items__c> orderItemsList)
{
//Code to create file here
csvBlob = Blob.valueOf(finalstr);
tDoc = new Document();
tDoc.Name = 'sales_items_' +date.today();
tDoc.Type = 'csv';
tDoc.body = csvBlob;
tDoc.FolderId = [select id from folder where name = 'Emarsys Order Files'].Id;
tDoc.ContentType = 'application/vnd.ms-excel';
Insert tDoc;
system.debug('doc inserted');
sendFile();
}
#Future(callout = true)
public static void sendFile()
{
System.debug('I am creating the post request');
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setMethod('POST');
request.setHeader('Authorization','Security Token');
request.setHeader('Accept','text/plain');
request.setHeader('Content-Type', 'text/csv');
request.setHeader('Authorization', 'Bearer ');
request.setBodyAsBlob(csvBlob);
HttpResponse response = http.send(request);
system.debug('response: ' + response);
}
So I tried again by doing it in the queueable apex class. The thing I was missing was "Database.AllowsCallouts" in the class heading. Below is my queueable class which is working with the batch class to send a rest post request.
public class OrderItemFilePostHelper implements System.Queueable,Database.AllowsCallouts
{
private Blob csvBlob;
public EmarsysOrderItemFilePostHelper(Blob csvBlob) {
this.csvBlob = csvBlob;
}
public void execute(System.QueueableContext objContext)
{
System.debug('I am creating the post request');
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setMethod('POST');
request.setHeader('Authorization','Security Token');
request.setHeader('Accept','text/plain');
request.setHeader('Content-Type', 'text/csv');
request.setHeader('Authorization', 'Bearer ');
request.setEndpoint('https://webhook.site/b0746268-e95c-4f94-bcb6-61d4bea54378');
request.setBodyAsBlob(csvBlob);
HttpResponse response = http.send(request);
system.debug('response: ' + response);
}
}

Signing AWS Api Gateway request in Unity3D C#

I'm using Unity3D v5.5.1, with AWS-SDK-Unity v3.3.37.0.
Since the Api Gateway doesn't generate an SDK for C#/Unity3D I'm trying to sign (SigV4) the request my self and have encountered difficulties.
I've tried both manually signing and using the AWS4Signer.cs class.
The Api Gateway method has the Invoke with caller credentials, and just returns a Hello World as a response.
Within unity I have a facebook login button which returns the FB credentials and tokens. Using Cognito Federated Identity's GetCredentialsAsync method I get an ImmutableCredentials object with the Key, Secret and a Token.
To access the api gateway url I'm using the AWS4Signer class here to construct a signed request. In the example below I've tried both adding the security token to the url parameters and without, also signing it and not signing with the token. All options don't work (As stated in this post)
This results in either the following responses:
1. The request signature we calculated does not match the signature you provided
The security token included in the request is invalid.
How can I correctly sign the request from Unity3D?
Thanks in advance
TestGet method:
IEnumerator TestGet (ImmutableCredentials response)
{
ApiGatewayConfig clientConfig = new ApiGatewayConfig(); // a class I created wrapping the ClientConfig.cs
var metrics = new RequestMetrics();
var awsAccessKeyId = response.AccessKey;
var awsSecretAccessKey = response.SecretKey;
var awsToken = response.Token;
AmazonWebServiceRequest req = new MyRequest(); // a clas I created wrapping the AmazonWebServiceRequest.cs class
var url = "https://<url_to_api>.execute-api.us-east-1.amazonaws.com/dev/securehello";
IRequest request = new DefaultRequest(req,"execute-api");
request.UseQueryString = true;
request.HttpMethod = "GET";
request.Endpoint = new System.Uri (url);
request.ResourcePath = url;
request.ContentStream = new MemoryStream();
request.Parameters.Add("X-Amz-Expires",AWS4PreSignedUrlSigner.MaxAWS4PreSignedUrlExpiry.ToString(CultureInfo.InvariantCulture));
request.AuthenticationRegion = "us-east-1";
request.AlternateEndpoint = RegionEndpoint.USEast1;
request.UseSigV4 = true;
request.Headers.Add("X-Amz-Security-Token",awsToken);
request.Parameters.Add("X-Amz-Security-Token",awsToken);
AWS4Signer signer = new AWS4Signer();
Debug.Log ("a");
signer.Sign(request,clientConfig,metrics,awsAccessKeyId,awsSecretAccessKey);
var signerRes = signer.SignRequest(request,clientConfig,metrics,awsAccessKeyId,awsSecretAccessKey);
Debug.Log ("b");
var myParams = string.Format("{0}&X-Amz-Security-Token={1}",signerRes.ForQueryParameters,awsToken);
var dict = myParams.Split('&').Select(p=> p.Split('=')).GroupBy(p => p[0]).Select(p => p.First()).ToDictionary(p => p[0], p=>System.Uri.UnescapeDataString(p[1]));
var myEncodedParams = string.Empty;
bool isFirst = true;
foreach (var key in dict.Keys) {
myEncodedParams += string.Format("{0}{1}={2}",isFirst ? "" : "&",key,WWW.EscapeURL(dict[key]));
isFirst = false;
}
var finalUrl = string.Format ("{0}?{1}", request.Endpoint.AbsoluteUri,myEncodedParams);
UnityWebRequest uwr = new UnityWebRequest (finalUrl, "GET", new DownloadHandlerBuffer (), null);
Debug.Log ( string.Format("\n\n\n{0}\n\n\n",finalUrl));
Debug.Log ("Starting WebRequest");
yield return uwr.Send();
if (uwr.isError) {
Debug.LogError (uwr.error);
} else {
Debug.Log (uwr.downloadHandler.text);
}
Helper classes:
public class ApiGatewayConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.3.37.0");
private string _userAgent = UserAgentString;
public ApiGatewayConfig ()
{
this.AuthenticationServiceName = "execute-api";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "execute-api";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2015-07-09";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
public class MyRequest : AmazonWebServiceRequest
{
public MyRequest () {}
}
Solved.
I've created some examples showing how to do this. Still work in progress, example shows how to sign a POST request from Unity 3D to Api Gateway endpoint that has "Invoke with caller credentials" (AWS_IAM).
Unity 3D Client:
https://github.com/guywald/serverless-auth-msg-board-unity3d-client
AWS Serverless backend (using Serverless Framework):
https://github.com/guywald/serverless-auth-msg-board

ionic - send push notification to Firebase from Ionic device [duplicate]

After searching the docs I could not find any info on how to send device to device messages using FCM without the use of an external server.
For example, if I was creating a chat application I would need to send push notifications to users about unread messages since they won't be online all the time and I can't have a persistent service in the background that would always be connected to the real time database because that would be too resource heavy.
So how would I send a push notification to a user "A" when a certain user "B" sends him/her a chat message? Do I need an external server for this or can it be done with just Firebase servers?
UPDATE: It is now possible to use firebase cloud functions as the server for handling push notifications. Check out their documentation here
============
According to the docs you must implement a server for handling push notifications in device to device communication.
Before you can write client apps that use Firebase Cloud Messaging, you must have an app server that meets the following criteria:
...
You'll need to decide which FCM connection server protocol(s) you want to use to enable your app server to interact with FCM connection servers. Note that if you want to use upstream messaging from your client applications, you must use XMPP. For a more detailed discussion of this, see Choosing an FCM Connection Server Protocol.
If you only need to send basic notifications to your users from the server. You can use their serverless solution, Firebase Notifications.
See a comparison here between FCM and Firebase Notifications:
https://firebase.google.com/support/faq/#messaging-difference
Making a HTTP POST request with the link https://fcm.googleapis.com/fcm/send with required header and data helped me. In the below code snippet
Constants.LEGACY_SERVER_KEY is a local class variable, you can find this at your Firebase Project Settings->Cloud Messaging->Legacy Server key. You need to pass device registration token i.e. regToken in below code snippet referenced HERE.
At last you need okhttp library dependency in order to get this snippet work.
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
private void sendNotification(final String regToken) {
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
OkHttpClient client = new OkHttpClient();
JSONObject json=new JSONObject();
JSONObject dataJson=new JSONObject();
dataJson.put("body","Hi this is sent from device to device");
dataJson.put("title","dummy title");
json.put("notification",dataJson);
json.put("to",regToken);
RequestBody body = RequestBody.create(JSON, json.toString());
Request request = new Request.Builder()
.header("Authorization","key="+Constants.LEGACY_SERVER_KEY)
.url("https://fcm.googleapis.com/fcm/send")
.post(body)
.build();
Response response = client.newCall(request).execute();
String finalResponse = response.body().string();
}catch (Exception e){
//Log.d(TAG,e+"");
}
return null;
}
}.execute();
}
further if you want to send message to a particular topic, replace regToken in json like this
json.put("to","/topics/foo-bar")
and don't forget to add INTERNET permission in your AndroidManifest.xml.
IMPORTANT : - Using above code means your server key resides in the client application. That is dangerous as someone can dig into your application and get the server key to send malicious notifications to your users.
You can do it using Volly Jsonobject request....
follow this Steps first:
1 copy legacy server key and store it as Legacy_SERVER_KEY
Legacy Server key
you can see in picture how to get
2 You need Volley dependency
compile 'com.mcxiaoke.volley:library:1.0.19'
Code for send Push:-
private void sendFCMPush() {
String Legacy_SERVER_KEY = YOUR_Legacy_SERVER_KEY;
String msg = "this is test message,.,,.,.";
String title = "my title";
String token = FCM_RECEIVER_TOKEN;
JSONObject obj = null;
JSONObject objData = null;
JSONObject dataobjData = null;
try {
obj = new JSONObject();
objData = new JSONObject();
objData.put("body", msg);
objData.put("title", title);
objData.put("sound", "default");
objData.put("icon", "icon_name"); // icon_name image must be there in drawable
objData.put("tag", token);
objData.put("priority", "high");
dataobjData = new JSONObject();
dataobjData.put("text", msg);
dataobjData.put("title", title);
obj.put("to", token);
//obj.put("priority", "high");
obj.put("notification", objData);
obj.put("data", dataobjData);
Log.e("!_#rj#_##_PASS:>", obj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, Constants.FCM_PUSH_URL, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("!_##_SUCESS", response + "");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("!_##_Errors--", error + "");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "key=" + Legacy_SERVER_KEY);
params.put("Content-Type", "application/json");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
int socketTimeout = 1000 * 60;// 60 seconds
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsObjRequest.setRetryPolicy(policy);
requestQueue.add(jsObjRequest);
}
Just Call sendFCMPush();
1) subscribe an identical topic name, for example:
ClientA.subcribe("to/topic_users_channel")
ClientB.subcribe("to/topic_users_channel")
2) send messages inside the application
GoogleFirebase : How-to send topic messages
Yes, it's possible to do it without any server. You can create a device group client side and then you exchange messages in the group. However there are limitations:
You have to use the same Google account on the devices
You can't send high priority messages
Reference: Firebase doc See the section "Managing device groups on Android client apps"
Google Cloud Functions make it now possible send push notifications from device-to-device without an app server.
I have made cloud function which is trigger when new message is added in database
It is node.js code
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin'); admin.initializeApp();
exports.sendNotification = functions.database.ref('/conversations/{chatLocation}/{messageLocation}')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const original = snapshot.val();
const toIDUser = original.toID;
const isGroupChat = original.isGroupChat;
if (isGroupChat) {
const tokenss = admin.database().ref(`/users/${toIDUser}/tokens`).once('value').then(function(snapshot) {
// Handle Promise
const tokenOfGroup = snapshot.val()
// get tokens from the database at particular location get values
const valuess = Object.keys(tokenOfGroup).map(k => tokenOfGroup[k]);
//console.log(' ____________ddd((999999ddd_________________ ' + valuess );
const payload = {
notification: {
title: original.senderName + " :- ",
body: original.content
}
};
return admin.messaging().sendToDevice(valuess, payload);
}, function(error) {
console.error(error);
});
return ;
} else {
// get token from the database at particular location
const tokenss = admin.database().ref(`/users/${toIDUser}/credentials`).once('value').then(function(snapshot) {
// Handle Promise
// The Promise was "fulfilled" (it succeeded).
const credentials = snapshot.val()
// console.log('snapshot ......snapshot.val().name****^^^^^^^^^^^^kensPromise****** :- ', credentials.name);
//console.log('snapshot.....****snapshot.val().token****^^^^^^^^^^^^kensPromise****** :- ', credentials.token);
const deviceToken = credentials.token;
const payload = {
notification: {
title: original.senderName + " :- ",
body: original.content
}
};
return admin.messaging().sendToDevice(deviceToken, payload);
}, function(error) {
console.error(error);
});
}
return ;
});
Google Cloud Functions make it now possible send push notifications from device-to-device without an app server.
From the relevant page on Google Cloud Functions:
Developers can use Cloud Functions to keep users engaged and up to
date with relevant information about an app. Consider, for example, an
app that allows users to follow one another's activities in the app.
In such an app, a function triggered by Realtime Database writes to
store new followers could create Firebase Cloud Messaging (FCM)
notifications to let the appropriate users know that they have gained
new followers.
Example:
The function triggers on writes to the Realtime Database path where followers are stored.
The function composes a message to send via FCM.
FCM sends the notification message to the user's device.
Here is a demo project for sending device-to-device push notifications with Firebase and Google Cloud Functions.
You can use firebase realtime database to do so. You can create data structure for storing chats and add observers for the conversation threads for both users. It still does device - server - device architecture, but in this case there is no additional server on the developers' part. This uses the firebase servers. You can check out a tutorial here (ignore the UI part, although, that is also a good starting point for chat UI frameworks).
Firebase Realtime Chat
If you have fcm(gcm) token of the device to whom you want to send notification. It's just a post request to send the notification.
https://github.com/prashanthd/google-services/blob/master/android/gcm/gcmsender/src/main/java/gcm/play/android/samples/com/gcmsender/GcmSender.java
In my case I use retrofit with this class Message:
public class Message {
private String to;
private String collapseKey;
private Notification notification;
private Data data;
public Message(String to, String collapseKey, Notification notification, Data data) {
this.to = to;
this.collapseKey = collapseKey;
this.notification = notification;
this.data = data;
}
}
Data
public class Data {
private String body;
private String title;
private String key1;
private String key2;
public Data(String body, String title, String key1, String key2) {
this.body = body;
this.title = title;
this.key1 = key1;
this.key2 = key2;
}
}
Notification
public class Notification {
private String body;
private String title;
public Notification(String body, String title) {
this.body = body;
this.title = title;
}
}
this the call
private void sentToNotification() {
String to = "YOUR_TOKEN";
String collapseKey = "";
Notification notification = new Notification("Hello bro", "title23");
Data data = new Data("Hello2", "title2", "key1", "key2");
Message notificationTask = new Message(to, collapseKey, notification, data);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://fcm.googleapis.com/")//url of FCM message server
.addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
.build();
ServiceAPI api = new retrofit.create(ServiceAPI.class);
Call<Message> call = api .sendMessage("key=YOUR_KEY", notificationTask);
call.enqueue(new Callback<Message>() {
#Override
public void onResponse(Call<Message> call, retrofit2.Response<Message> response) {
Log.d("TAG", response.body().toString());
}
#Override
public void onFailure(Call<Message> call, Throwable t) {
Log.e("TAG", t.getMessage());
}
});
}
our ServiceAPi
public interface ServiceAPI {
#POST("/fcm/send")
Call<Message> sendMessage(#Header("Authorization") String token, #Body Message message);
}
You can use Retrofit. Subscribe devices to topic news. Send notification from one device to other.
public void onClick(View view) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", "key=legacy server key from FB console"); // <-- this is the important line
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
httpClient.addInterceptor(logging);
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://fcm.googleapis.com")//url of FCM message server
.client(client)
.addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
.build();
// prepare call in Retrofit 2.0
FirebaseAPI firebaseAPI = retrofit.create(FirebaseAPI.class);
//for messaging server
NotifyData notifydata = new NotifyData("Notification title","Notification body");
Call<Message> call2 = firebaseAPI.sendMessage(new Message("topic or deviceID", notifydata));
call2.enqueue(new Callback<Message>() {
#Override
public void onResponse(Call<Message> call, Response<Message> response) {
Log.d("Response ", "onResponse");
t1.setText("Notification sent");
}
#Override
public void onFailure(Call<Message> call, Throwable t) {
Log.d("Response ", "onFailure");
t1.setText("Notification failure");
}
});
}
POJOs
public class Message {
String to;
NotifyData notification;
public Message(String to, NotifyData notification) {
this.to = to;
this.notification = notification;
}
}
and
public class NotifyData {
String title;
String body;
public NotifyData(String title, String body ) {
this.title = title;
this.body = body;
}
}
and FirebaseAPI
public interface FirebaseAPI {
#POST("/fcm/send")
Call<Message> sendMessage(#Body Message message);
}
Here is walk around how to get notifications without second server apart from the Firebase one. So we use Firebase only, without additional server.
At the mobile app code, we create its own notifications function by Android libraries like here, not using Firebase libraries like here, without Firebase Cloud messaging.
Here is an example with Kotlin:
private fun notification() {
createNotificationChannel()
val intent = Intent(this, LoginActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
val notificationBuilder = NotificationCompat.Builder(this, "yuh_channel_id")
.setSmallIcon(R.drawable.ic_send)
.setContentText("yuh")
.setContentText("yuh")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
with(NotificationManagerCompat.from(this)) {
// notificationId is a unique int for each notification that you must define
notify(0, notificationBuilder.build())
}
}
private fun createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "yuh_channel"
val descriptionText = "yuh_description"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val CHANNEL_ID = "yuh_channel_id"
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
In the Firebase database, create collection "pending notifications". Documents should contain user name (to send notification to) and source name (where should user go upon tapping the notification).
In the app code, implement option for adding new records to the Pending Notifications collection. E. g. if user A sends message to user B, then the document with the id of user B (who will be notified) is created in the collection.
In the app code, set up background (when the app is not visible to the user) service. Like here. In the background service, set up a listener for changes in the "Notifications Pending" collection. When the new record with the user id comes to the collection, call the notification function created in the paragrath 1 supra and delete the consequent record from the collection.
So I had an idea here. See: If the FCM, as well as the GCM, has a endpoit to http request where we can send a post json with our message data, including the token (s) of devices that we want this message to be delivered.
So why not send a post to Firebase server with this notification to be delivered to user B? you understand ?
So, you send the message and chat with a call post to ensure delivery of the notification if the user is with your app in the background. I am also in need of it soon, I will test later. What do you say about?
Simplest way :
void sendFCMPush(String msg,String token) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", "key="+Const.FIREBASE_LEGACY_SERVER_KEY); // <-- this is the important line
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
httpClient.addInterceptor(logging);
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://fcm.googleapis.com/")//url of FCM message server
.client(client)
.addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
.build();
// prepare call in Retrofit 2.0
FirebaseAPI firebaseAPI = retrofit.create(FirebaseAPI.class);
//for messaging server
NotifyData notifydata = new NotifyData("Chatting", msg);
Call<Message> call2 = firebaseAPI.sendMessage(new Message(token, notifydata));
call2.enqueue(new Callback<Message>() {
#Override
public void onResponse(Call<Message> call, retrofit2.Response<Message> response) {
Log.e("## SUCCES #E$#", response.body().toString());
}
#Override
public void onFailure(Call<Message> call, Throwable t) {
Log.e("E$ FAILURE E$#", t.getMessage());
}
});
}
Create Class to make Object:
public class Message {
String to;
NotifyData data;
public Message(String to, NotifyData data) {
this.to = to;
this.data = data;
}
}
Create Class to make Object:
public class Notification {
String title;
String message;
enter code here`enter code here`
public Notification(String title, String message) {
this.title = title;
this.message = message;
}
}

Invoking Camel Rest services gives me 401 using restlet

I am trying write a route to call a restful services. all of them donot have a body but query parameters. when i call(https) the rest service i get 401(unauthorised).
but if i use simple non-ssl (http) and invoke it works fine on other apis.
here is my Route and producer template.
Route
public static final String MONITOR_URI = "https://lsapi.thomson-pharma.com//ls-api-ws/ws/rs/opportunity-v1/match?drug=bevacizumab&company=Genentech Inc&fmt=json";
public static final String DIRECT_MONITOR = "direct:getDrugInfo";
from(DIRECT_MONITOR).to(MONITOR_URI).convertBodyTo(String.class);
=========================Main Class===============================
public static void main(String[] args) throws Exception {
CamelContext context = createCamelContext();
context.start();
final String text = "paracetamol";
final String fmt = "json";
final String authMethod = "Digest";
final String authUsername = "TR_Internal_024";
final String authPassword="ZTYA5S1KLF7WCDMN";
final String query = String.format("text=%s&fmt=%s&authMethod=%s&authUsername=%s&authPassword=%s",text,fmt,authMethod,authUsername,authPassword);
Map<String,Object> headers = new HashMap<String, Object>(){
{
put(Exchange.HTTP_METHOD,"POST");
put(Exchange.AUTHENTICATION,"Digest");
put("authUsername","TR_Internal_024");
put("authPassword","ZTYA5S1KLF7WCDMN");
put(Exchange.HTTP_QUERY,query);
}
};
ProducerTemplate template = context.createProducerTemplate();
String request = template.requestBodyAndHeaders(Constants.DIRECT_MONITOR,null,headers,String.class);
System.out.println("Body is : "+request);
}
Can someone help how to configure SSL using camel cxf or restlet ?
How do i add Credentials Provider to CamelContext or Spring Context ?
APologies for the delay. i got it worked by retriving the component from camelContext below is the code.
=========================================================================
HttpComponent http = (HttpComponent) camelContext.getComponent("https");
HttpClientConfigurer httpClientConfigurer = http.getHttpClientConfigurer();
if(httpClientConfigurer == null){
System.out.println("httpClientConfigurer is null");
if(http.getHttpClientConfigurer() == null ){
HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.setAuthMethod(AuthMethod.Digest);
httpConfiguration.setAuthUsername("xxxxx");
httpConfiguration.setAuthPassword("xxxxxx");
http.setHttpConfiguration(httpConfiguration);
}
}
Regards
Ram

Web API HttpClient PutAsync returning Http 404

Im trying to send a PUT to my Web API and am struggling a bit as to how I should construct the actual Http request. Below is an integration test sample. It works fine using HttpMessageInvoker to call the Web API Put, but I want to use HttpClient in test also since that is what I'll be using in the business layer.
[TestMethod]
public void Verify_UpdateBudgetData_Http_PUT()
{
int budgetId = 1;
string appId = "DummyApp";
string userId = "Dummy";
string value = "400";
string filterJSON =
"{dimensionFilter:{\"Demo_Konto\":[\"3000\"],\"Demo_AO\":[\"200\"]},valueSpreadType:{\"Value1\":0}}";
HttpConfiguration config = new HttpConfiguration();
Konstrukt.SL.AggregationEngine.WebApiConfig.Register(config, new SL.AggregationEngine.AutofacStandardModule());
HttpServer server = new HttpServer(config);
/*this works*/
using (HttpMessageInvoker client = new HttpMessageInvoker(server))
{
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put,
String.Format("http://localhost/AggregationEngine/UpdateBudgetData/{0}/{1}/{2}/{3}/{4}",
budgetId, appId, userId, value, filterJSON)))
using (HttpResponseMessage response = client.SendAsync(request, CancellationToken.None).Result)
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Wrong http status returned");
}
};
/*this does not work*/
using (var client = new HttpClient())
{
//client.BaseAddress = new Uri("http://localhost");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var responseMessage =
client.PutAsync(
String.Format("http://localhost/AggregationEngine/UpdateBudgetData/{0}/{1}/{2}/{3}/{4}",
budgetId, appId, userId, value, filterJSON), new StringContent("")).Result;
Assert.AreEqual(HttpStatusCode.OK, responseMessage.StatusCode, "Wrong http status returned");
}
}
Here is my WebApiConfig-class
public static class WebApiConfig
{
public static void Register(HttpConfiguration config, Autofac.Module moduleToAppend)
{
config.Routes.MapHttpRoute(
name: "UpdateBudgetData",
routeTemplate: "AggregationEngine/{controller}/{budgetId}/{appId}/{userId}/{value}/{filterJSON}",
defaults: new { filter = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "GetBudgetAndRefData",
routeTemplate: "AggregationEngine/{controller}/{budgetId}/{userId}/{filterJSON}",
defaults: new { filter = RouteParameter.Optional }
);
config.EnableCors();
config.EnableSystemDiagnosticsTracing();
// Autofac container
// if not configured here you'll not have dependencies provided to your WebApiControllers when called
var builder = new ContainerBuilder(); // yes, it is a different container here
builder.RegisterAssemblyTypes( // register Web API Controllers
Assembly.GetExecutingAssembly())
.Where(t =>
!t.IsAbstract && typeof(ApiController).IsAssignableFrom(t))
.InstancePerLifetimeScope();
// register your graph - shared
builder.RegisterModule(
new AutofacStandardModule()); // same as with ASP.NET MVC Controllers
if (moduleToAppend != null)
{
builder.RegisterModule(moduleToAppend);
}
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(
container);
}
public static void Register(HttpConfiguration config)
{
Register(config, null);
}
}
How can I fix the HttpClient call to PutAsync? Should I embed the FilterJSON parameter in the body? If so, how to do that? I've tried that but then the FromBody parametger was null...
I got it working by using the FromBody tag in the controller and then wrapping that parameter in the http request body. An important note to is to prefix the parameter with an "=" sign to make sure it was interpreted correctly by the controller. Also I removed the same parameter from the route config. Finally to make the client to server request work I had to replace HttpServer Class with httpselfhostserver