set parameters to ejb timer task to perform backend process - java

I used EJB Timer task to perform my periodic service query to database and send the update to client within specific period. This period is defined by client.
I pass the client request to the ejb timer stateless session bean. The request is stored as a instance variable.
When I call timer task through JNDI I set the client request to this instance variable and its available before timerService.createTimer() call. But when the #Timeout happen the instance variable is null.
I need this client request to perform DB query to find request parameters.
#Stateless
public class PeriodicService implements TimerRemote{
#Override
public void initializeTimer(Date firstDate, long timeout, String info) throws RemoteException {
try {
// below line show the request is not null.
System.out.println("request in initializeTimer "+this.request);
// create onetime service now.
timerService.createTimer(firstDate, info);
log.info("Timer created at " + firstDate + " with info: " + info);
} catch (Exception e) {
log.fatal("Exception after create timer : "+ e.toString());
e.printStackTrace();
}
}
#Timeout
public void ejbTimeout(Timer arg0) {
// below line show the requst as null
log.debug("Request in ejbTimeout "+this.request);
}
public void setRequest(IVEFRequest request) {
this.request = request;
}
private IVEFRequest request = null;
}
I'm new to EJB. Some thing wrong the way I do it? or how can I keep the request variable available until I cancel/stop the timer

You can try below code, no need to create a separate instance variable.
Provide the object that you would like to receive in timeout method while creating timer.
timerService.createTimer(firstDate, request);
Then, fetch the object in timeout method which was passed at timer creation.
(IVEFRequest)arg0.getInfo();

Related

Invoking Scheduler from a Rest Controller

I have a Spring MVC project and Im currently trying to invoke a scheduler task from my restController. I have created a StartupBean and which contains a start() that actually invokes the TimerTask. Sample code below
public void start() throws Exception {
LOGGER.info("Entering start method {}", System.currentTimeMillis());
try {
// running timer task as daemon thread
TimerTask counterTimerTask = new SessionCountTask();
Timer counterTimer = new Timer(true);
counterTimer.scheduleAtFixedRate(counterTimerTask, 0, (long) 10 * 1000);//10 sec
} catch (Exception e) {
LOGGER.error("Error in start method of startup Bean {}", e);
} finally {
LOGGER.info("Exiting start method {}", System.currentTimeMillis());
}
}
From the Rest controller, Im just invoking the above start() method of the StartupBean. The above method doesnot return anything. The SessionCountTask class contains a method which returns a JSON object. I wanted to know how I can get the json response to the controller. The scheduler is scheduled to run every 10 secs and I would like to know how to get the response from the task every 10sec and display in the controller.
Any help on this is much appreciated.
Thanks in Advance.

Calling another GRPC service from a constructor

In GRPC...what is the most efficient of calling another GRPC service before it can answer to any request?
My code here looks a bit of a mess... in the constructor of the GreetingServiceImpl, I am starting a Thread just to get
some sort of Greetings list from a GreetingServiceRepository service running on a different port?
So the use case is something like this... There is a GRPC service GreetingsRepository which contains a list of greetings and
a GreetingServiceImpl which calls the GreetingsRepository.. I wanted to customize the response so that I can return a custom response
for every request....
public class MyGrpcServer {
static public void main(String [] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(8080)
.addService(new GreetingServiceImpl()).build();
System.out.println("Starting server...");
server.start();
System.out.println("Server started!");
server.awaitTermination();
}
public static class GreetingServiceImpl extends GreetingServiceGrpc.GreetingServiceImplBase {
public GreetingServiceImpl(){
init();
}
public void init(){
//Do initial long running task
//Like running a thread that will call another service from a repository
Thread t1 = new Thread(){
public void run(){
//Call another grpc service
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8081)
.usePlaintext(true)
.build();
GreetingServiceRepository.eGreetingServiceRepositoryBlockingStub stub =
GreetingServiceRepositoryGrpc.newBlockingStub(channel);
//Do something with the response
}
}
t1.start();
}
#Override
public void greeting(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
System.out.println(request);
//USE THE LIST OF GREETINGS FROM THE REPOSITORY and customize it per user
//String greeting = "Hello there, " + request.getName();
//String greeting = "Holla, " + request.getName();
String greeting = "Good Morning, " + request.getName();
HelloResponse response = HelloResponse.newBuilder().setGreeting(greeting).build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
}
Is there a way in GRPC to initialize the service before it can respond to any other request?
I am not sure if constructor is a good idea..and firing up another thread just to call another service.
There's two major ways: 1) delay starting the server until dependent services are ready, and 2) delay clients sending requests to this server, until dependent services are ready.
Delay starting the server until ready:
GreetingServiceImpl gsi = new GreetingServiceImpl();
Server server = ServerBuilder.forPort(8080)
.addService(gsi).build();
System.out.println("Starting server...");
gsi.init();
server.start();
Delaying clients sending requests to this server depends on how clients learn of the server's address. For example, if using a load balancing proxy that uses the Health service, wait until ready and then call:
healthStatusManager.setStatus("", ServingStatus.SERVING);
The proxy will then learn this server is healthy and inform clients about the backend.

How to send multiple asynchronous requests in parallel using Unirest

While using Unirest, the program doesn't exit until we manually shutdown every thread by invoking Unirest.shutdown(). If I had to make just one request, it's easy:
private static void asyncRequest (String link) {
try {
Future <HttpResponse <JsonNode>> request = Unirest.head(link).asJsonAsync(
new Callback<JsonNode>() {
#Override
public void completed(HttpResponse<JsonNode> httpResponse) {
print(httpResponse.getHeaders());
try {
Unirest.shutdown();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void failed(UnirestException e) {
print(e.getMessage());
}
#Override
public void cancelled() {
print("Request cancelled");
}
}
);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
asyncRequest("https://entrepreneur.com");
}
But I have to make multiple HTTP request in parallel (subsequent requests are meant not to wait for previous requests to complete). In the code above, I have to execute the code inside asyncRequest more than once with different links. The problem is I can't decide when to invoke Unirest.shutdown() so that the program exits as soon as the last request receives response. If I call Unirest.shutdown() after all the calls to asyncRequest in main, some or all the requests might get interrupted. If I call it inside completed (and other overridden methods), only the first request is made and others are interrupted. How can I solve this?
In theory, you could make the current thread wait for the execution of the method and after they are all done you can call the shutdown. But this would make the whole process synchronous, which is not what we want. So what I would do is, run different thread (other than the main one) which will wait for the execution of all your http requests. To do so you can use the class CountDownLatch, initializing with the countdown before it releases the control to the parent thread. You pass the instance of the CountDownLatch to the async method and you decrease by one each time you complete an http request. When it reaches 0 it returns the control to the parent thread, where you know you can call shutdown method as all your requests are done.

General purpose network manager in Android

I'm working on an Android project (API level 10) which needs to send and receive http messages to/from a server.
I implemented a class named NetworkManager which provides different methods, one for each http request (e.g.: loginRequest(user pass), RegistrationRequest(user.....) ).
All these methods generates a JSON object that is passed to the method called sendMessage, which is the method that actually establish the connection, sends and receives the response (also a json object).
Of course network calls are time consuming, so i first decided to use an AsyncTask to display a progressDialog while the network operation is being performed.
The problem is that i need to get the response value retrived from the background thread before executing any other operation which involves the result itself done by the Main thread.
At the same time i would like to make a common and reusable implementation of the AsyncTask.
E.g.: I have a login activity which shows 2 EditText (username, password) and a button called Login. When I press the login button, a progressDialog must appear, and must be disposed once the doInBackground task is accomplished. Of course i could do this way:
onClick(View v) //called when the login button is pressed
{
onPreExecute()
{
//Show the progress dialog
}
doInBackground()
{
//Retreive the login response (an integer containing a message code) using sendLoginRequest(username, password);
//return the response
}
onPostExecute(int response)
{
//Dispose the progress dialog, then loginSucessfull ? start new activity : show error toast
}
}
But, doing this way i should implement an async task for every request i need to send which is what i would like to avoid because if i have N requests i should create N classes that extend AsyncTask.
Thank you!
What i would suggest you is to use INTERFACES for handling response of http request.
The background thread either it be a AysncTask or it be Thread needs to handle both
response
exception
Think it like this way
MainThread - Hey Background Thread do this operation and let me know when you are done.
MainThread - Ok till Background Thread executes its operation let me show progress dialog.
BackGroundThread - I am done with my work. hey MainThread here catch you response or exception
MainThread - Let me stop showing progress bar.
So we need to simulate this callback mechanism via code and also needs to take care that we implement a reusable architecture.
Something like this
Define a Interface
public interface HttpRequestResponse {
public void onSuccess(HttpResponse response);
public void onException(Exception exception);
}
class HttpRequestResponseHandler {
private ActionItem action;
private HttpRequestResponse hrr;
private Executor executor;
public enum ActionItem {
LOGIN_REQUEST ,
REGISTRATION_REQUEST
}
public HttpRequestResponseHandler(ActionItem action, HttpRequestResponse hrr) {
this.action = action;
this.hrr = hrr;
}
public void execute(){
executor = new Executor();
executor.execute();
}
private class Executor extends AsyncTask<Void,Void,Void> {
#Override
public Void doInBackground() {
switch(action) {
case LOGIN_REQUEST : doLogin();
break;
case REGISTRATION_REQUEST : doRegistration();
break;
}
}
}
private void doLogin() {
HttpResponse response = null;
Exception exception = null;
try {
response = makeHttpRequestHere();
} catch (Exception e) {
exception = e;
}
if(exception != null) {
hrr.onException(exception);
} else {
hrr.onSuccess(response);
}
}
}
Now in somewhere in your activity code file do like this.
HttpRequestResponse hrr = new HttpRequestResponse(){
#Override
public void onSuccess(HttpResponse response) {
hideProgressDialog();
handleResponse(response);
}
#Override
public void onException(Exception exception) {
hideProgressDialog();
showErrorDialog(exception.getMessage());
}
}
HttpRequestResponseHandler hrrh = new HttpRequestResponseHandler(ActionItem.LOGIN_REQUEST,hrr);
hrrh.execute();
showProgressDialog();
Hope all this lead to what you want.
Its been a long answer and took quite a effort of mine to figure. :)
why not just using AsyncTask.THREAD_POOL_EXECUTOR(Runnable run);
It wraps a thread pool based executor of #cores + 1 parallelity level.
Then you can simply invoke:
AsyncTask.THREAD_POOL_EXECUTOR(new Runnable(){
public void run(){
doLogin();
});

Android: Executing method from specific thread

I'm developing an application in Android. The application can post a HTTP request to specific web server. That post request must run asyncronously, so I create a thread to do the job. But I need a callback that will be called at thread end and it must be called from thread that call the `post` method.
My post method looks like this:
interface EndCallback
{
public void Success(String response);
public void Fail(Exception e);
}
public void post(final String url, final List<NameValuePair> data, EndCallback callback)
{
Thread t = Thread.currentThread();
(new Thread()
{
public void run()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try
{
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse r = httpclient.execute(httppost);
HttpEntity en = r.getEntity();
String response = EntityUtils.toString(en);
//I want to call callback.Success(response)
//here from thread t
}
catch (Exception ex)
{
//And I want to call callback.Fail(ex)
//here from thread t
}
}
}).start();
}
You may want to use a Handler. Handler is used to post requests to GUI thread.
For success handling, use following code:
final Handler successHandler = new Handler()
{
#Override
public void handleMessage(Message message)
{
callback.Success(response);
}
};
successHandler.sendEmptyMessage(0);
Creating new threads an Android is highly discouraged for most applications. This seems like the perfect place for an AsyncTask. It has built-in methods that switch between threads, without needing to manually manage thread creation.
One approach I've used in a similar situation is to combine the task with an enum of possible success states:
class HttpPostTask extends AsyncTask<Void, Void, ResponseStatus> {
#Override
protected ResponseStatus doInBackground( Void... params ){
try {
// do your HTTP stuff
return ResponseStatus.SUCCESS;
} catch( Exception e ){
return ResponseStatus.FAILURE;
}
}
#Override
protected void onPostExecute( ResponseStatus status ){
switch( status ){
case SUCCESS:
// run your success callback
break;
case FAILURE:
// run the failure callback
break;
}
}
}
enum ResponseStatus {
SUCCESS,
FAILURE
}
The doInBackground method will be run in a separate thread, managed by the OS. When that thread finishes, onPostExecute will be run on the thread that started the task, which is typically the UI thread.
If you need to set up callback objects, just add a constructor to the HttpPostTask and do any initialization you need. Your client code will then just need to create and execute the task:
new HttpPostTask().execute();
You can also pass parameters into execute() as well, which accepts a variable number of arguments of the first generic type in the class signature. The params variable in the doInBackground is an array of things that were passed into execute, all of the same type.
Passing params into execute is useful if, for example, you wanted to post to multiple URLs. For most dependencies, setting them in the constructor is simplest approach.

Categories

Resources