Can I get multiple response from micro Service which will Query MongoDB - java

I have Service which will give us response back by querying MongoDB on the basis of some parameter provided
#RequestMapping(value = "/custRef/{custRef}", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<String> getServiceId(#PathVariable("custRef") String custRef) throws InterruptedException {
System.out.println("Thread.currentThread().getName() :"+Thread.currentThread().getName());
String serviceId=//calling Mongo Service and getting the result
if(custRef == null) {
return new ResponseEntity<String>("No service id available for the given FO Id:" + custRef,HttpStatus.NOT_FOUND);
}
return new ResponseEntity<String>(serviceId,HttpStatus.OK);
}
I have another client which will call the above service by providing the proper parameter. I want to call the above service by using 10 threads. can I get the response back in same frequency from the above service or do I need to do any configuration on the server where above one is running
ExecutorService es = Executors.newFixedThreadPool(50);
for (RouterInfo router : listOfcpeRouterInfo){
Future<String> serviceIDS = es.submit(new CalculationTaskA(router.getCustomerRef(), rieClient));
}
#Override
public String call() throws Exception {
String currentThreadName = Thread.currentThread().getName();
log.info("##### [" + currentThreadName + "] <" + taskId + "> STARTIING #####");
// System.out.println("[" + currentThreadName + "] <" + taskId + ">
// Sleeping for " + sleepTime + " millis");
// TimeUnit.MILLISECONDS.sleep(sleepTime);
//
String serviceId = null;
try {
///
serviceId = rieClient.getObject(customerRef);
log.info("serviceId for given foid: " + customerRef + " is " + serviceId);
} catch (ParseException pe) {
log.error("error while parsing Data", pe);
}
log.info("****** [" + currentThreadName + "] <" + taskId + "> DONE ******");
return serviceId;
}
calling above service
enter code here
Inside getObject I am doing below
ResponseEntity<String> response=restTemplate.exchange(this.serviceIdUrl+"/{foId}",HttpMethod.GET,entity,String.class,foId);

By default, Spring Boot applications are multithreaded so your code sample
ExecutorService es = Executors.newFixedThreadPool(50);
for (RouterInfo router : listOfcpeRouterInfo){ Future serviceIDS = es.submit(new CalculationTaskA(router.getCustomerRef(), rieClient)); }
would only be needed in your "Mongo" Service if asynchronous calls are to be made by the "Mongo" service.

Related

Add reaction in jda to Message by messageid

My problem is, that my code, especially tc.addReactionById(messageID, emote);, dont adds a reaction. The whole code is following!
if(args[0].equalsIgnoreCase(prefix + "system") && args[1].equalsIgnoreCase("radd")){
if(args.length == 6){
Message message = event.getMessage();
List<TextChannel> channels = event.getMessage().getMentionedChannels();
List<Role> roles = message.getMentionedRoles();
if(!channels.isEmpty() && !roles.isEmpty()){
TextChannel tc = event.getMessage().getMentionedChannels().get(0);
Role role = roles.get(0);
String messageIDString = args[2];
try{
long messageID = Long.parseLong(messageIDString);
String emote = args[5];
tc.addReactionById(messageID, emote);
eb.setAuthor("Oni System");
eb.setColor(Color.MAGENTA);
eb.setDescription(emote);
eb.setFooter("Oni System | ©ONI", "https://media.discordapp.net/attachments/810910771557957672/810927512892604416/Bot.png?width=676&height=676");
channel.sendMessage(eb.build()).queue();
LiteSQL.onUpdate("INSERT INTO reactionroles(guildid, channelid, messageid, emoji, roleid) VALUES(" + event.getGuild().getIdLong() + ", " + tc.getIdLong() + ", " + messageID + ", '" + emote +"', " + role.getIdLong() + ")");
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
else{
eb.setAuthor("Oni System");
eb.setColor(Color.RED);
eb.setDescription(userMent + " bitte benutze !system radd <messageid> <#role> <channel> <emoji>");
eb.setFooter("Oni System | ©ONI", "https://media.discordapp.net/attachments/810910771557957672/810927512892604416/Bot.png?width=676&height=676");
channel.sendMessage(eb.build()).queue();
}
}
addReactionById is a RestAction in the JDA library, so you will need to queue the operation.
Replace
tc.addReactionById(messageID, emote);
with
tc.addReactionById(messageID, emote).queue();
Assuming the messageID and emote arguments are valid, the call to .queue() should process the reaction. In particular, emote needs to be one of either:
An Emote object created by JDA (usually these are custom server emotes), or
A Unicode string of the emoji you want to add
See the MessageChannel documentation for more info.

400 bad request without error message - Twitter API

Hey guys!
I'm currently trying to create an app that uses the Twitter API to get timelines of users. I'm currently stuck at a specific point! My user has already logged in and I've already received the access token and the token secret. I'm now trying to send a get request to the Twitter server.
My problem is that I'm always getting a 400 bad request error code WITHOUT any kind of message.
I'm using Volley to send the requests - Heres the code
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Response Time: " + error.getNetworkTimeMs() + " ms");
Log.e(TAG, "Code: " + error.networkResponse.statusCode);
Log.e(TAG, "Data: " + new String(error.networkResponse.data));
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
Long tsLong = System.currentTimeMillis() / 1000;
//I receive all the difference parts
String consumerKey = context.getString(R.string.twitter_consumer_key);
String nonce = GenerationHelper.generateNonce();
String signature_method = "HMAC-SHA1";
String timestamp = tsLong.toString();
String token = sTwitterToken;
String version = "1.0";
// I use this list to pass the parameters to the function
// generating the signature
List<String> param= new ArrayList<>();
param.add("screen_name=" + username);
param.add("count=" + count);
param.add("oauth_token" + sTwitterToken);
param.add("oauth_consumer_key=" + consumerKey);
param.add("oauth_nonce=" + nonce);
param.add("oauth_signature_method=" + signature_method);
param.add("oauth_timestamp=" + timestamp);
param.add("oauth_version=" + version);
String signature = GenerationHelper.generateSignature(context, param, "POST", "https://api.twitter.com/1.1/statuses/user_timeline.json");
// I create the header String
StringBuilder paramBuilder = new StringBuilder();
paramBuilder.append("oauth_consumer_key=\"" + consumerKey + "\", ");
paramBuilder.append("oauth_nonce=\"" + nonce + "\", ");
paramBuilder.append("oauth_signature=\"" + signature + "\", ");
paramBuilder.append("oauth_signature_method=\"" + "HMAC-SHA1" + "\", ");
paramBuilder.append("oauth_timestamp=\"" + timestamp + "\", ");
paramBuilder.append("oauth_token=\"" + sTwitterToken + "\", ");
paramBuilder.append("oauth_version=\"" + "1.0" + "\"");
String credentialString = paramBuilder.toString();
Log.d(TAG, credentialString);
params.put("Authorization", "OAuth " + credentialString);
return params;
}
};
My current response is
Code: 400
Data:
If I remove the line adding the authorization data I get the response
Code: 400
Data: {"errors":[{"code":215,"message":"Bad Authentication data."}]}
I'm pretty sure that I don't get rate limited because I'm just sending about 10 requests per 15 minutes.
Does anybody have any idea why I'm having this problem?

Parallel Execution: How to update Excel WorkBook using Synchronized method, only after synchronized method execution is completed?

I have written a non-static synchronized method in a class to avoid multiple threads updating the Excel Workbook at the same time. For example Thread with ID #9 and #10 are trying to update Excel, expected is that Thread#9 should complete the operation of synchronized method and then Thread#10 should be able to invoke the method which is not happening for us. Below is the code snippet.
public synchronized boolean put(String parameterName, String parameterValue) {
try {
System.out.println("Start Time:= " + Thread.currentThread().getId() + " :: " + LocalDateTime.now().toString());
updateData(data.get("XLFileName"), data.get("XLSheetName"), parameterName, parameterValue, data.get("TestCaseID"), data.get("Iteration"));
System.out.println("End Time:= " + Thread.currentThread().getId() + " :: " + LocalDateTime.now().toString());
return true;
} catch (FilloException flex) {
flex.printStackTrace();
// extentTest.log(LogStatus.FATAL, "A", flex.getMessage());
return false;
}
}
public void updateData(String XLFileName, String XLSheet, String parameterName, String parameterValue, String testCaseID, String iteration) throws FilloException {
Fillo fillo = new Fillo();
Connection connection = fillo.getConnection(XLFileName);
String strQuery = "Update " + XLSheet + " Set " + parameterName + "='" + parameterValue + "' where TestCaseID = '" + testCaseID + "' and Iteration = '" + iteration + "'";
connection.executeUpdate(strQuery);
connection.close();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Current Output:
Start Time:= 10 :: 2017-03-20T15:03:31.041
1 row(s) affected
Start Time:= 9 :: 2017-03-20T15:03:31.619
1 row(s) affected
End Time:= 10 :: 2017-03-20T15:03:41.201
End Time:= 9 :: 2017-03-20T15:03:41.675
Expected Output:
Start Time:= 10 :: 2017-03-20T15:03:31.041
1 row(s) affected
End Time:= 10 :: 2017-03-20T15:03:41.201
Start Time:= 9 :: 2017-03-20T15:03:31.619
1 row(s) affected
End Time:= 9 :: 2017-03-20T15:03:41.675
Tried with synchronized block as well.
Can you try with Synchronized block with lock on class as shown below.
public synchronized boolean put(String parameterName, String parameterValue) {
synchronized (DataBook.class) {
try {
System.out.println("Start Time:= " + Thread.currentThread().getId() + " :: " + LocalDateTime.now().toString());
updateData(data.get("XLFileName"), data.get("XLSheetName"), parameterName, parameterValue, data.get("TestCaseID"), data.get("Iteration"));
System.out.println("End Time:= " + Thread.currentThread().getId() + " :: " + LocalDateTime.now().toString());
return true;
} catch (FilloException flex) {
flex.printStackTrace();
return false;
}
}
}
Since this is not static, the lock used here is an intrinsic lock, i.e. a lock per object. What it means is that you have a lock per thread, so each thread has the right to execute its own put method, thus the output you observe.
What I would suggest to obtain the desired output is to make this method static, so that the lock is associated to the class, and only one Thread will be able to access it at a time, giving you the expected output (or almost, thread 9 could start sooner than Thread 10):
public static synchronized boolean put(String parameterName, String parameterValue)

How to avoid repeating try block

I'm coding a webservice in Java using aws and in many method i need to have a try catch block that can actually log any errors that can occur in the execution of each exposed methods.
#WebMethod(operationName = "listingBucket")
public String listingBucket() {
String message = "";
try {
message = "Listing buckets";
for (Bucket bucket : s3.listBuckets()) {
message += " - " + bucket.getName();
}
} catch (AmazonServiceException ase) {
message += "Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.";
message += "Error Message: " + ase.getMessage();
message += "HTTP Status Code: " + ase.getStatusCode();
message += "AWS Error Code: " + ase.getErrorCode();
message += "Error Type: " + ase.getErrorType();
message += "Request ID: " + ase.getRequestId();
} catch (AmazonClientException ace) {
message += "Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with S3, "
+ "such as not being able to access the network.";
message += "Error Message: " + ace.getMessage();
}
return message;
}
#WebMethod(operationName = "addObjectToBucket")
public String addObjectToBucket(String bucketName, String objectName, File file) throws IOException{
if ( file == null ){
file = createSampleFile();
}
String message = "";
try {
message += "Uploading a new object to S3 from a file\n";
s3.putObject(new PutObjectRequest(bucketName, objectName, file));
} catch (AmazonServiceException ase) {
message += "Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.";
message += "Error Message: " + ase.getMessage();
message += "HTTP Status Code: " + ase.getStatusCode();
message += "AWS Error Code: " + ase.getErrorCode();
message += "Error Type: " + ase.getErrorType();
message += "Request ID: " + ase.getRequestId();
} catch (AmazonClientException ace) {
message += "Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with S3, "
+ "such as not being able to access the network.";
message += "Error Message: " + ace.getMessage();
}
return message;
}
How Can i avoid to repeat this try catch block throw all methods that use this kind of stuff ?
Thanks for your help !
Edit : Actually I modified the code :
private String parseError(AmazonServiceException ase) {
String message;
message = "Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.";
message += "Error Message: " + ase.getMessage();
message += "HTTP Status Code: " + ase.getStatusCode();
message += "AWS Error Code: " + ase.getErrorCode();
message += "Error Type: " + ase.getErrorType();
message += "Request ID: " + ase.getRequestId();
return message;
}
private String parseError(AmazonClientException ace) {
String message;
message += "Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with S3, "
+ "such as not being able to access the network.";
message += "Error Message: " + ace.getMessage();
return message;
}
#WebMethod(operationName = "listingBucket")
public String listingBucket() {
String message = "";
try {
message = "Listing buckets";
for (Bucket bucket : s3.listBuckets()) {
message += " - " + bucket.getName();
}
} catch (AmazonServiceException exc) {
message += parseError(exc);
} catch (AmazonClientException exc) {
message += parseError(exc);
}
return message;
}
Clearer indeed ! :)
I'll just take a look about the command pattern to see if I can use it for this kind of application.
There are two aspects in here.
One thing is about the code repetition in the catch block; which can be easily turned into something like
public class ExceptionHandler {
public String buildMessageFor(AmazonServiceException ase) {
... }
public String buildMessageFor(AmazonClientException ase) {
... }
...
You can even unit test that thing very easily (where "naming" could be improved; but I guess the example should be good enough to get you going).
That would also make it easier in the future to turn from "pure string" messages into something else. You know, hardcoding user messages in source code is not the smartest thing to do.
The other part, the try/catch itself; somehow depends. You see, the try/catch is an essential part of your operations; so many people would argue that you simply keep that structure in your code. The only alternative would be to define some kind of interface like
public interface RunAmazonOperation {
public void run() throws Amazon...
}
Then you can write down all your operations as little classes implementing that interface; to be called by some framework that does the try/catch for you. If that is worth the price ... depends on your application.
In other words: if you turn to the "command" pattern; you might find it useful to define a variety of "commands"; implementing that interface; thus reducing the number of places with try/catch dramatically.
Just do it with methods. One possibility would look like:
String parseError(AmazonServiceException ase){
String message;
message = "Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.";
message += "Error Message: " + ase.getMessage();
message += "HTTP Status Code: " + ase.getStatusCode();
message += "AWS Error Code: " + ase.getErrorCode();
message += "Error Type: " + ase.getErrorType();
message += "Request ID: " + ase.getRequestId();
return message;
}
String parseError(AmazonClientException ace){
String message;
message = "Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with S3, "
+ "such as not being able to access the network.";
message += "Error Message: " + ace.getMessage();
return message;
}
Now you can just write:
catch(AmazonServiceException exc){
message=parseError(exc);
}
catch(AmazonClientException exc){
message=parseError(exc);
}

How do I list Quartz running jobs in java/struts2

I wanted to list all the Quartz's jobs, which are running on background. I'm using following code, but I'm not getting any list.
public class RunningJobs {
public void getJobList() throws SchedulerException {
Scheduler schedule = new StdSchedulerFactory().getScheduler();
System.out.println(schedule.getJobGroupNames().size()+" "+schedule.isShutdown());
for (String groupName : schedule.getJobGroupNames()) {
for (JobKey jobKey : schedule.getJobKeys(GroupMatcher
.jobGroupEquals(groupName))) {
String jobName = jobKey.getName();
String jobGroup = jobKey.getGroup();
List<Trigger> triggers = (List<Trigger>) schedule
.getTriggersOfJob(jobKey);
Date nextFireTime = triggers.get(0).getNextFireTime();
System.out.println("[jobName] : " + jobName + " [groupName] : "
+ jobGroup + " - " + nextFireTime);
}
}
}
}
Although, there are few jobs, which are keep on running using web application struts2.
The call to getScheduler is providing you with a new scheduler, which does not contain the jobs. You need to get a handle to the scheduler containing the actual jobs, through one of two ways.
Iterate through all schedulers:
for(Scheduler schedule :StdSchedulerFactory().getAllSchedulers()){
System.out.println(schedule.getJobGroupNames().size()+" "+schedule.isShutdown());
for (String groupName : schedule.getJobGroupNames()) {
for (JobKey jobKey : schedule.getJobKeys(GroupMatcher
.jobGroupEquals(groupName))) {
String jobName = jobKey.getName();
String jobGroup = jobKey.getGroup();
List<Trigger> triggers = (List<Trigger>) schedule
.getTriggersOfJob(jobKey);
Date nextFireTime = triggers.get(0).getNextFireTime();
System.out.println("[jobName] : " + jobName + " [groupName] : "
+ jobGroup + " - " + nextFireTime);
}
}
}
Or getting a scheduler by name:
Scheduler schedule = new StdSchedulerFactory().getScheduler("schedulerName");

Categories