nodejs and java api performance comparison - java

I have done a performance test of an REST API which is inserting data into MongoDB and also developed two applications using Java and Nodejs Express.
For testing, I have used JMeter which is invoking API 10 times (10 users) and realised that Java gave me consistent performance but Nodejs didn't.
Sometimes Nodejs app is taking more than 2ms to insert simple records into MongoDB.
As I have heard that Nodejs is faster for IO applications but did not find it.
Can someone tell me why I am not getting that performance or is my understanding or result I got is correct?
note: I am Java expert, learning Nodejs.
UPDATE :
I have created rest api which will insert records in mongodb and I am using mongoose to insert it . below is my code -
router.post("/", (req, res, next) => {
const order = new Order({
_id: new mongoose.Types.ObjectId(),
email: req.body.name,
uid: req.body.uid,
});
console.log(order);
order.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "Order is successfully added",
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});

Related

com.facebook.react.bridge.NativeArgumentsParseException: RNGooglePlaces.openAutocompleteModal got 3 arguments, expected 4

I'm trying to implement Places autocomplete in my react native application.
Previously i was using react-native-google-places version 2.5.2 every thing was working fine. Recently i updated to recent version 3.1.2.
openSearchModal() {
RNGooglePlaces.openAutocompleteModal({
type: 'establishment',
})
.then((place, err) => {
this.setState({ placeObj: place.address, selectedPlace: place.name });
this.props.callback(place);
console.log(err);
})
.catch(error => console.log(error.message));
// error is a Javascript Error object
}
The above is the code which will be triggered onButton press.
Every thing works fine in Debug mode.
But when i make the release build i'm getting this error.
com.facebook.react.bridge.NativeArgumentsParseException: RNGooglePlaces.openAutocompleteModal got 3 arguments, expected 4
Can any one please help me with this.

Firebase access Hackernews

So i wanted to check out Firebase and try connecting to Hackernews Firebase database.
I'm using the com.google.firebase:firebase-server-sdk:3.0.3 sdk.
But I am not sure why i am forced to enter a service account.
#Bean
fun firebase(): DatabaseReference {
val options = FirebaseOptions.Builder()
.setDatabaseUrl("https://hacker-news.firebaseio.com/")
.setServiceAccount(this.javaClass.getResourceAsStream("/account.json"))
.build()
val app = FirebaseApp.initializeApp(options)
val instance = FirebaseDatabase.getInstance(app)
return instance.reference
}
Why is setServiceAccount required in this case ? If i leave it out i get following exception:
Caused by: java.lang.IllegalStateException: Service Account must be provided.
at com.google.firebase.internal.Preconditions.checkState(Preconditions.java:173) ~[firebase-server-sdk-3.0.3.jar:na]
at com.google.firebase.FirebaseOptions.<init>(FirebaseOptions.java:129) ~[firebase-server-sdk-3.0.3.jar:na]
Is there a way to connect to Firebase anonymously with a Java client?
This JsFiddle works without a service account:
http://jsfiddle.net/firebase/cm8ne9nh/
If i connect to my own project, this work perfectly nice. I do have a proper service account for my own projects thought...
Thought i might be able to connect with Java the same way.
Any ideas ? Is there a way to connect to Hackernews with the Firebase Java API?
Unfortunately, the Java SDK is only available in two flavors. Java-Client-Android, and Java-Server. Which means, if you want pure client code, you can only really use it on android. This has always been a strange limitation of the available client libraries.
However, what you can do, is wrap the REST API that firebase provides with Java, using HTTP requests to perform everything like you would in any client library.
An example of a repository that has already implemented this is here: https://github.com/j-fischer/rest-on-fire
You could use that one, or you could use your own. But in order to use firebase without a service account, you will have to either use the REST Api or the official Client Libraries which are only writen for Android, iOS, and Web.
Although in the docs here it is not obvious
https://github.com/HackerNews/API
I found this REST API that does not need authentication:
https://hn.algolia.com/api
It can be used in many ways, including with Retrofit & Moshi and no authentication.
Just one example in Kotlin:
interface HackerNewsService {
#GET("search?tags=(story,show_hn,front_page)&hitsPerPage=500")
fun searchStories(#Query("query") q: String, #Query("numericFilters") filters: String, #Query("page") page: Int): Call<SearchResult>
}
val response = hackerNewsService.searchStories(keyword, "created_at_i>$after", 0).execute()
if (response.isSuccessful) {
val searchResult: SearchResult = response.body()!!
println("results! (${searchResult.hits.size}) $searchResult")
} else {
println("uh oh")
}

Retrieving sending statistics applicable to Amazon SES service

I am writing Java app which sends email via Amazon SES service, and that works fine. But now I need to retrieve email sending statistics as granural as per email ID basis.
So, I use CloudWatch and pass the notifications to SNS. Yet, I cannot infer away how to get the statistics as per explicit request to the Web service. The SNS endpoints are able to dispatch the data as on needing basis. When I want to make explicit request from my app on service for stats.
The S3 service is for storage. Do I need to store stats somehow on it, so that later I can query it?
Any resolutions and details are appretiated?
Hi For your requirement as per my understanding AWS Dynamo DB is the best way. AWS Dynamo DB is a No sql related DB. After sending email you can store the result (emailId, if you want time ect..) into Dynamo DB by using SNS, or nay lambda functions. You can fire a query to dynamo DB to get the statistics.
If you want to go with S3 bucket way, you have a maintain one json file, and each time need to overwrite that file.
Well, this is the way I got the sending stats.
When it comes to Amazon SES, it gives you very limited sending statistics; not pointing to particular sent email.
Then when it comes to Amazon Cloudwatch, it gives you very similar statistics as the SES, is that it gives you a chance to make the stats dates appear precise to the extend of minutes. Meaning that if you know when you sent the email, via SES, by storing it on DB, you can estimate which stat belongs to which email.
Then you can use the Amazon Firehose combined with Amazon S3. This is where I landed. The Firehose is a stream which pushes statistics on the S3 storage. The SES provides the configuration set which lets you attach it.
The S3 stores anything you like, including email sending statistics. You can have up to 5 stats:
Send
Delivered
Bounce
Complaint
Reject
The stats are stored in files which you can access and read by using Amazon's SDK pertaining to Java language.The way to query in Java
What you get then is JSON file of email sending statistics, e.g.,
{
"eventType":"Bounce",
"bounce":{
"bounceType":"Permanent",
"bounceSubType":"General",
"bouncedRecipients":[
{
"emailAddress":"recipient#example.com",
"action":"failed",
"status":"5.1.1",
"diagnosticCode":"smtp; 550 5.1.1 user unknown"
}
],
"timestamp":"2016-10-14T05:02:52.574Z",
"feedbackId":"EXAMPLE7c1923f27-ab0c24cb-5d9f-4e77-99b8-85e4cb3a33bb-000000",
"reportingMTA":"dsn; ses-example.com"
},
"mail":{
"timestamp":"2016-10-14T05:02:16.645Z",
"source":"sender#example.com",
"sourceArn":"arn:aws:ses:us-east-1:123456789012:identity/sender#example.com",
"sendingAccountId":"123456789012",
"messageId":"EXAMPLE7c191be45-e9aedb9a-02f9-4d12-a87d-dd0099a07f8a-000000",
"destination":[
"recipient#example.com"
],
"headersTruncated":false,
"headers":[
{
"name":"From",
"value":"sender#example.com"
},
{
"name":"To",
"value":"recipient#example.com"
},
{
"name":"Subject",
"value":"Email Subject"
},
{
"name":"MIME-Version",
"value":"1.0"
},
{
"name":"Content-Type",
"value":"multipart/mixed; boundary=\"----=_Part_0_716996660.1476421336341\""
},
{
"name":"X-SES-MESSAGE-TAGS",
"value":"myCustomTag1=myCustomTagValue1, myCustomTag2=myCustomTagValue2"
}
],
"commonHeaders":{
"from":[
"sender#example.com"
],
"to":[
"recipient#example.com"
],
"messageId":"EXAMPLE7c191be45-e9aedb9a-02f9-4d12-a87d-dd0099a07f8a-000000",
"subject":"Email Subject"
},
"tags":{
"ses:configuration-set":[
"my-configuration-set"
],
"ses:source-ip":[
"192.0.2.0"
],
"ses:from-domain":[
"example.com"
],
"ses:caller-identity":[
"ses_user"
],
"myCustomTag1":[
"myCustomTagValue1"
],
"myCustomTag2":[
"myCustomTagValue2"
]
}
}
}
That is about it.

Async JavaScript connection with Java and passing parameters

I am sorry, I know the question is pretty stupid, but I am pretty new at Java, I've been working a lot with .NET.
With .NET I was using the following function to gather data and receive response from another page:
$.ajaxSetup({
global: false,
timeout: 60000,
type: "POST"
});
$.getJSON("Async/GetRegionalData",
{
requestedFunction: "getData",
id: 1
},
function (data) {
if (data != null) {
if (!data.ErrorCode == "0") {
}
else {
//function goes here
}
}
}
});
My question is this: How can I achieve the same thing with Java file as a server side?
Any links to relative topics would be of help.
How to get the parameters in the url that is requested? Anything connected with this topic is helpful. I did some research, but I didn't find much regarding this topic. Thank you in advance.

PHP Long Polling Issues

I have a web application which serves as the Admin Panel. It has a live chat option which connects with writers(employees) on the other end. The web application uses the following PHP code to check for online writers.
$q = 0;
$lasttime = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
while ($q<5){
sleep(3);
$wresult = $db->query("SELECT writer_alias FROM tblwriter WHERE writer_isactive=1 AND (UNIX_TIMESTAMP(NOW())-last_activity)<10");
if ($wresult->num_rows){ break; }
++$q;
}
if ($wresult->num_rows){
while ($row = $wresult->fetch_object()){ $writers[] = $row; }
$wresult->free();
}
echo json_encode(
array(
"writers" => $writers,
"now" => time()
)
);
On the application the following javascript code handles the PHP response and calls ajax again to complete the loop.
function UpdateCHAT(){
$.ajax({
type: "POST",
url: "liveserver.php",
data: {update:"1",timestamp:lastime},
success:
function(data1){
if (data1 == null){
$(".onlinechat i").removeClass("icon-white");
}else{
lastime = user_signin = Number(data1.now);
if (!data1.writers.length){
$(".onlinechat i").removeClass("icon-white");
}else{
$(".onlinechat i").removeClass("icon-white");
$.each(data1.writers,function(j) {
$("#writer_"+data1.writers[j].writer_alias).find("i").addClass("icon-white");
});
}
}
},
dataType: "json",
timeout: 60000,
complete:
function(){
UpdateCHAT();
}
}
);
}
Everything is working just fine except the fact that I cannot think of a way to know for offline writers since the PHP code is designed to check for the online writers, but this means if a writer is online once, he will remain online (on the application) until the PHP code dies and return empty writers.
Hope I am able to explain my point. This question is more to do with idea rather than piece of code. Any input is appreciated.
Thanks.
Make the PHP code always return after some time (like 2 minutes) with an empty result set (ie. no new chat lines).
JS will then do a new request immediately. If it doesn't, well, then the user is offline. Keep a last_request timestamp, if it's older than 2+e minutes the user is offline.
You could try to detect when the connection closes in PHP. Set ignore_user_abort(true) so you are in control of when your script dies. Then use connection_aborted() to check if the client closed. If he did you know he left.
A potential problem occurs if the user has two windows open: a close on one doesn't mean he left, but this may turn out to be acceptable; the user will blip for just a while.
Another solution is to use a separate ping request that just tells you "yep, I'm still here". If you haven't gotten one of those in a while the user is probably offline.

Categories

Resources