I want to write the firebase notification as a String like JSON format .. I already sent the notification for one device but when trying to send to multiple devices i got bad request ..
params = new StringEntity("{\n" +
" \"to\" : \"ds1YTh...UUZOos\",\n" +
" \"notification\" : {\n" +
" \"body\" : \""+jobTitle+"\",\n" +
" \"title\" : \"New Job!\",\n" +
" \"icon\" : \"hire\"\n" +
" \"sound\" : \"default\"\n"+
" \"time_to_live\" : "+3600+
" }\n" +
" \"data\": {"+
" }"+
" }");
how could i do that .. and if I can't do it this way what is the best way to implement this .. I'm using HttpClient and HttpPost and primefaces 5.3
First a few relevant links:
Sending notifications to multiple devices not subscribed to a certain topic
the Firebase documentation on sending downstream messages
the Firebase documentation on sending to multiple devices (which covers using topics and device groups)
FCM (Firebase Cloud Messaging) Send to multiple devices
But if you want to stick closest to your current code, you should be able to specify the device tokens in a registration_ids property:
params = new StringEntity("{\n" +
" \"registration_ids\" : [\"ds1YTh...UUZOos\", \"et2ZUi...VVUPpt\"],\n" +
" \"notification\" : {\n" +
" \"body\" : \""+jobTitle+"\",\n" +
" \"title\" : \"New Job!\",\n" +
" \"icon\" : \"hire\"\n" +
" \"sound\" : \"default\"\n"+
" \"time_to_live\" : "+3600+
" }\n" +
" \"data\": {"+
" }"+
" }");
I have done it in Asp.net I hope it will help in some way...
for (int i = 0; i < dt.Rows.Count (No. of Rows or Device); i++)
{
tRequest.ContentType = "application/json";
var data1 = new
{
to="" + DeviceID + "",
priority="high",
notification = new
{
body = Message,
is_background = true,
title = Heading,
appicon = "http://webbestsites.com/images/1_icon.png",
sound = "default"
},
}
Related
I'm using Java High level rest client in my project and i want to limit my indices based on document count. I'm using rollover api but its not creating indices automatically.
The code will be given below.
I'm creating index pattern so that my custom analyzer will be applied to all other indices that follow the respective pattern.
PutIndexTemplateRequest request = new PutIndexTemplateRequest("testingtemplate");
request.source("{\n" +
" \"index_patterns\":[\n" +
" \"test_log-*\"\n" +
" ],\n" +
" \"settings\": {\n" +
" \"analysis\": {\n" +
" \"analyzer\": { \n" +
" \"my_analyzer\": {\n" +
" \"type\": \"custom\",\n" +
" \"tokenizer\": \"whitespace\",\n" +
" \"filter\": []\n" +
" }\n" +
" }\n" +
" }\n" +
" },\n" +
" \"mappings\": {\n" +
" \"properties\": {\n" +
" \"fullLog\": {\n" +
" \"type\": \"text\",\n" +
" \"analyzer\": \"my_analyzer\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }",XContentType.JSON);
return client.indices().putTemplate(request,RequestOptions.DEFAULT).isAcknowledged();
My Rollover code. Here i want to rollover one when index gets one or document.
final RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
boolean isIndexTemplateCreated = createIndexTemplate(client);
System.out.println(isIndexTemplateCreated);
CreateIndexRequest request = new CreateIndexRequest("test_log-1");
request.alias(new Alias("temp_alias_new"));
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
RolloverRequest roll_req = new RolloverRequest("temp_alias_new",null);
roll_req.addMaxIndexAgeCondition(new TimeValue(7, TimeUnit.DAYS));
roll_req.addMaxIndexDocsCondition(1);
roll_req.addMaxIndexSizeCondition(new ByteSizeValue(5, ByteSizeUnit.GB));
RolloverResponse rolloverResponse = client.indices().rollover(roll_req, RequestOptions.DEFAULT);
Map<String,Object> map = new HashMap<>();
map.put("fullLog","Hi");
client.index(new IndexRequest("temp_alias_new").source(map), RequestOptions.DEFAULT);
map.put("fullLog","hello");
client.index(new IndexRequest("temp_alias_new").source(map), RequestOptions.DEFAULT);
But the code is not working and the rollover api is not creating indices automatically. All the 2 documents are stored only in test_log-1 index.
Is there any mistake in my code?
Thanks
Note: Rollover will not happen automatically.
Elasticsearch tries to rollover the index on getting a rollover request.
For example consider the following sequences:
You have a new index test_log-1 which is empty and is being pointed by the alias temp_alias_new.
If you try to rollover now, none of the conditions mentioned along with rollover request holds good as the index is new and empty. So this time rollover fails.
Add some documents to the index.
Now try the rollover with the condition maxIndexDocsCondition(1), it will rollover. Because the condition holds good.
Update
With the latest release of elastic search, you can use ILM (Index Life cycle Management) to automate the rollover.
Here is doc link for more info: https://www.elastic.co/guide/en/elasticsearch/reference/7.x/getting-started-index-lifecycle-management.html
Using AWS SDK for JAVA, i want to limit access to a single Bucket folder.
When i try to run this code to assign permissions to a new IAM user:
final AmazonIdentityManagement client = AmazonIdentityManagementClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(Regions.US_EAST_2)
.build();
try {
String permissionsBoundary =
"{" +
"\"Version\": \"2012-10-17\"," +
" \"Statement\": [" +
" {" +
" \"Effect\": \"Allow\"," +
" \"Action\": "+
" [" +
" \"s3:PutObject\"," +
" \"s3:GetObject\"," +
" \"s3:DeleteObject\"" +
" ]," +
" \"Resource\": \"arn:aws:s3:::mybucket/*\"" +
" }" +
" ]" +
"}";
CreateUserRequest request = new CreateUserRequest()
.withUserName(usernameIAM)
.withPermissionsBoundary(permissionsBoundary);
CreateUserResult response = client.createUser(request);
i get this error:
ARN {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:ListAllMyBuckets","Resource":"arn:aws:s3:::*"}]} is not valid. (Service: AmazonIdentityManagement; Status Code: 400; Error Code: InvalidInput; Request ID: ...xxxxxxxxxxxx...)[Ljava.lang.StackTraceElement;#2f3a60a1
i followed this
Amazon IAM Policy
what is the correct use of the method withPermissionsBoundary and how is the rule correctly defined?
The error message says the following:
ARN
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "s3:ListAllMyBuckets",
"Resource": "arn:aws:s3:::*"
}
]
}
is not valid.
This is clearly not a valid ARN, because it isn't an ARN at all, it is a policy. Where is this used in your code? Wherever it is used, you need to replace it with the correct ARN.
I would want to send statistical information to my clients showing the number of transactions processed on every terminal or branch. I am using Apache Commons Email to send HTML emails.
I would like to send a pie-chart data like this one on the site.
My java code is basic extracted from.
It goes like:
public void testHtmlEmailPiechart()
throws UnsupportedEncodingException, EmailException, MalformedURLException {
HtmlEmail email = new HtmlEmail();
email.setHostName(emailServer);
email.setSmtpPort(587);
email.setSSLOnConnect(true);
email.setAuthentication(userName, password);
email.setCharset(emailEncoding);
email.addTo(receiver, "Mwesigye John Bosco");
email.setFrom(userName, "Enovate system emailing alert");
email.setSubject("Conkev aml Engine Statistics");
URL url = new URL("https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcROXe8tn1ljtctM53TkLJhLs6gEX56CvL0shvyq1V6wg7tXUDH8KRyVP30");
// URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
String cid2 = email.embed(url, "logo.gif");
email.setHtmlMsg("<html>\n" +
" <head>\n" +
" <script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n" +
" <script type=\"text/javascript\">\n" +
" google.charts.load(\"current\", {packages:[\"corechart\"]});\n" +
" google.charts.setOnLoadCallback(drawChart);\n" +
" function drawChart() {\n" +
" var data = google.visualization.arrayToDataTable([\n" +
" ['Task', 'Hours per Day'],\n" +
" ['Work', 11],\n" +
" ['Eat', 2],\n" +
" ['Commute', 2],\n" +
" ['Watch TV', 2],\n" +
" ['Sleep', 7]\n" +
" ]);\n" +
"\n" +
" var options = {\n" +
" title: 'My Daily Activities',\n" +
" is3D: true,\n" +
" };\n" +
"\n" +
" var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));\n" +
" chart.draw(data, options);\n" +
" }\n" +
" </script>\n" +
" </head>\n" +
" <body>\n" +
" <div id=\"piechart_3d\" style=\"width: 900px; height: 500px;\">Piechart Data</div>\n" +
" </body>\n" +
"</html>");
email.setTextMsg("Your email client does not support HTML messages");
email.send();
}
My guess is that the JavaScript is not recognized because the code works like sending images,styling fonts and I have sent to my email address some sample mail. I would like your help or recommendation of any material I can read to achieve this as long as am using Java.The processes is automated running in the background so no user interface is involved.
Thanks.
I have this code:
public void foo (){
String script =
"var aLocation = {};" +
"var aOffer = {};" +
"var aAdData = " +
"{ " +
"location: aLocation, " +
"offer: aOffer " +
" };" +
"var aClientEnv = " +
" { " +
" sessionid: \"\", " +
" cookie: \"\", " +
" rtserver-id: 1, " +
" lon: 34.847, " +
" lat: 32.123, " +
" venue: \"\", " +
" venue_context: \"\", " +
" source: \"\"," + // One of the following (string) values: ADS_PIN_INFO,
// ADS_0SPEED_INFO, ADS_LINE_SEARCH_INFO,
// ADS_ARROW_NEARBY_INFO, ADS_CATEGORY_AUTOCOMPLETE_INFO,
// ADS_HISTORY_LIST_INFO
// (this field is also called "channel")
" locale: \"\"" + // ISO639-1 language code (2-5 characters), supported formats:
" };" +
"W.setOffer(aAdData, aClientEnv);";
javascriptExecutor.executeScript(script);
}
I have two q:
when I debug and copy script value I see a member rtserver - id instead of rtserver-id
how can it be? the code throws an exception because of this.
Even if i remove this rtserver-id member (and there is not exception thrown)
I evaluate aLocation in this browser console and get "variable not defined". How can this be?
rtserver-id isn't a valid identifier - so if you want it as a field/property name, you need to quote it. You can see this in a Chrome Javascript console, with no need for any Java involved:
> var aClientEnv = { sessionId: "", rtserver-id: 1 };
Uncaught SyntaxError: Unexpected token -
> var aClientEnv = { sessionId: "", "rtserver-id": 1 };
undefined
> aClientEnv
Object {sessionId: "", rtserver-id: 1}
Basically I don't think anything's adding spaces - you've just got an invalid script. You can easily add the quotes in your Java code:
" \"rtserver-id\": 1, " +
We call a webservice from our C# app which takes about 300ms using WCF (BasicHttpBinding). We noticed that the same SOAP call does only take about 30ms when sending it from SOAP UI.
Now we also implemented a test accessing the webservice via a basic WebClient in order to make sure that the DeSer-part of the WCf is not the reason for this additional delay. When using the WebClient class the call takes about 300ms as well.
Any ideas on why Java compared to C# is about 10x faster in this regard? Is there some kind of tweaking possible on the .NET side of things?
private void Button_Click(object sender, RoutedEventArgs e)
{
executeTest(() =>
{
var resultObj = client.getNextSeqNr(new WcfClient()
{
domain = "?",
hostname = "?",
ipaddress = "?",
loginVersion = "?",
processId = "?",
program = "?",
userId = "?",
userIdPw = "?",
userName = "?"
}, "?", "?");
});
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
WebClient webClient = new WebClient();
executeTest(()=>
{
webClient.Proxy = null;
webClient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
webClient.Headers.Add("Content-Type", "application/xml");
webClient.Encoding = Encoding.UTF8;
var data = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"SomeNamespace\">" +
" <soapenv:Header/>" +
" <soapenv:Body>" +
" <ser:getNextSeqNr>" +
" <!--Optional:-->" +
" <clientInfo>" +
" <!--Optional:-->" +
" <domain>?</domain>" +
" <!--Optional:-->" +
" <hostname>?</hostname>" +
" <!--Optional:-->" +
" <ipaddress>?</ipaddress>" +
" <!--Optional:-->" +
" <loginVersion>?</loginVersion>" +
" <!--Optional:-->" +
" <processId>?</processId>" +
" <!--Optional:-->" +
" <program>?</program>" +
" <!--Optional:-->" +
" <userId>*</userId>" +
" <!--Optional:-->" +
" <userIdPw>?</userIdPw>" +
" <!--Optional:-->" +
" <userName>?</userName>" +
" </clientInfo>" +
" <!--Optional:-->" +
" <name>?</name>" +
" <!--Optional:-->" +
" <schema>?</schema>" +
" </ser:getNextSeqNr>" +
" </soapenv:Body>" +
"</soapenv:Envelope>";
string result = webClient.UploadString("http://server:8080/service", "POST", data);
});
}
Am I missing something here? Any idea would be helpful... ;-)
Kind regards,
Sebastian
I just found the reason for this.
It's the 100-Expect Continue HTTP Header and the corresponding implementation in .NET. The .NET client wait 350ms as default on the server. This causes the delays. Java seems to have other default values here...
Just add the following line of code very early in your code:
System.Net.ServicePointManager.Expect100Continue = false;
Cheers!