im using play framework 2.1.1 and java ,
im submitting a form and i can insert the data to the database,
also im sending mail by using the wonderful mailer plugin
what will be the best way to perform both action paralleled instead of one after the other ,
should i use ThreadPools or there is a more simple solution.
UPDATE SOLUTION :
this is how i solve it in the end
private static void sendMailHelper(final UserData formData) {
Akka.system().scheduler().scheduleOnce(
Duration.create(10, TimeUnit.SECONDS),
new Runnable() {
public void run() {
SendMail.sendMail(formData);
}
}, Akka.system().dispatcher());
}
i sent mail 10 sec after the user submit the form
If you are using Scala, then these pages should help you:
http://docs.scala-lang.org/overviews/core/futures.html
http://www.playframework.com/documentation/2.1.1/ScalaAsync
If you are using Java, then these pages should help you:
http://www.playframework.com/documentation/2.1.1/JavaAsync (as Carsten pointed out)
You could also use Akka Actors, check this page:
http://www.playframework.com/documentation/2.1.1/JavaAkka
Related
I am trying to do live streaming example app, where I can live update the list in the browser. I want to return all elements and then still listening (don't stop the stream) when new item is add to the database. Then I want to show new item in the browser. My current solution all the time prints all items (second by second) but I think there is better solution, when I can a) find the difference in list from last processing repository.findAll() and return only currList - prevList b) I can listen to some kind of events? Like inserting to table and add new item to still opened stream.
Here is my current code:
#RestController
#RequestMapping("/songs")
public class SongController {
private final SongRepository songRepository;
public SongController(SongRepository songRepository) {
this.songRepository = songRepository;
}
#GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Song> getAllSongs() {
return Flux.interval(Duration.ofSeconds(1))
.flatMap(x -> songRepository.findAll());
}
#PostMapping
public Mono<Song> addSong(#RequestBody Song song) {
return songRepository.save(song);
}
}
Here is how it looks like now:
As you can see, Its obviously looped, and I just need plain list with 7 elements on begining and then +1 element every time I post new song (by addSong()).
I don't need a entire ready solution, I just don't know what should I use.
Thank you in advance, cheers
In my experience there are three options that have different pros and cons.
You could create a web socket connection from the browser to your backend service. This will create a bi-directional connection that will allow you push updates from the server to your browser. In this instance whenever you add a song you would then write that song to the web socket connection and handle that on the browser side, so adding it to the list in the browser.
The cons of this are in my experience web socket connections are finicky and aren't the most stable or reliable.
You could use server side events. I haven't used this personally but I have heard this can be a viable options for pushing events from the server to the browser. https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
You could poll the endpoint. I know this approach gets a lot of hate in recent years but it is a viable options. The benefit with polling the endpoint is that it is resilient to failures. If your backend is overloaded and can't respond for one request it will likely be able to respond to a subsequent request. Also there are ways of improving commonly used endpoints so you're not hammering your database like a cache or something of that nature.
In my application i need to sync database with server, where tons of records (approx 300k). I am using paging concept to download data in my application using AsyncTask and Http connection in doInBackground(). I want to download pages concurrently and save into database. Is it a good approach to run AsynTask in loop like below or is there a better way to do this?
for (int i = 0 ;i <totalPage ; i++){
updateRecords(i);
}
private void updateRecords(int page) {
UpdateRecordsAsyncTask updateRecordsAsyncTask = new UpdateRecordsAsyncTask(this, mContext);
updateRecordsAsyncTask.setAsyncErrorListener(this);
updateRecordsAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Param);
}
You can use Service instead of AsnycTask. Being handling huge data that needed to be downloaded/upload. AsyncTask is definitely intended to run operations in background, but not such long operations.
If you need to interact with Activity , you can create call backs from service to intimate the UI. Go through the below links for the same 1) Stackoverflow link 2) Service Tutorial3) Android Service Tutorial4) Service with call backs
Use IntentService for downloading data from background.
More clarification please visit following url.
[1]: http://developer.android.com/reference/android/app/IntentService.html
What I want is to get database updates.
i.e If any changes occur to the database or a new record is inserted it should notify to the user.
Up to know what I implemented is using jQuery as shown below
$(document).ready(function() {
var updateInterval = setInterval(function() {
$('#chat').load('Db.jsp?elect=<%=emesg%>');
},1000);
});
It worked fine for me, but my teacher told to me that it's not a good way to do recommended using comet or long polling technology.
Can anyone give me examples for getting database updates using comet or long polling
in servlets/jsp? I'm using Tomcat as server.
Just taking a shot in the dark since I don't know your exact environment... You could have the database trigger fire a call to a servlet each time a row is committed which would then run some code that looked like the following:
Get the script sessions that are active for the page that we want to update. This eliminates the need to check every reverse ajax script session that is running on the site. Once we have the script sessions we can use the second code block to take some data and update a table on the client side. All that the second code section does is send javascript to the client to be executed via the reverse ajax connection that is open.
String page = ServerContextFactory.get().getContextPath() + "/reverseajax/clock.html";
Browser.withPage(page, new Runnable() {
public void run() {
Util.setValue("clockDisplay", output);
}
});
// Creates a new Person bean.
Person person = new Person(true);
// Creates a multi-dimensional array, containing a row and the rows column data.
String[][] data = {
{person.getId(), person.getName(), person.getAddress(), person.getAge()+"", person.isSuperhero()+""}
};
// Call DWR's util which adds rows into a table. peopleTable is the id of the tbody and
// data conta
ins the row/column data.
Util.addRows("peopleTable", data);
Note that both of the above sections of code are pulled straight from the documentation examples # http://directwebremoting.org/dwr-demo/. These are only simple examples of how reverse ajax can sent data to the client, but your exact situation seems to be more dependent on how you receive the notification than how you update the client screen.
Without some type of database notification to the java code I think you will have to poll the system at set intervals. You could make the system a little more efficient even when polling by verifying that there are reverse ajax script sessions active for the page before polling the database for info.
I was looking through for some solutions to read a file after uploading and I found this:
Read text file in google GWT?
that has a solution of
new RequestBuilder(Method.GET, "path/to/file.txt").sendRequest("", new RequestCallback() {
#Override
public void onResponseReceived(Request req, Response resp) {
String text = resp.getText();
// do stuff with the text
}
#Override
public void onError(Request res, Throwable throwable) {
// handle errors
}
});
It seems to be a feasible solution for my case, but I am kinda new to this, can any one explain how can I apply this in gwt? i have FileUpload placed in a panel already and a click handler to handle the submit button click.
Can someone help me out with this?
The answer you link to is for reading files from the server. They are just requesting the file from the webserver. It sounds like you want to read files from the client (you are using a FileUpload). There are different methods of doing that based on the stack your app is running on and what clients you support.
The GWT FileUpload is just an input control on the form which allows the user to pick a file. It does not do any part of the actual file reading.
A common approach is to send the file as part of the HTML form to the server and then reflect it back to the client to get it into your web app. This site is a little old but is great at giving you the basics of this approach. There are several examples using this with GWT: for example which also links to this. This option has the widest client support, but costs more in network traffic.
If you know the clients support HTML5 you can also read the file in JavaScript using the File API. Here are some docs from Mozilla. Unfortunately, there's not really integrated GWT support for it, so you'll have to write some JavaScript. This option will not be supported by all clients, but also doesn't generate any network traffic.
I am working in online application, in which there is facility of creating group. I want facility to send mail to all group user when any activity done in group. like comments , start new discussion etc. But problem is that . if any small activity i send thorusand of mail at run time. it slow the performance.
For that i am thinking to create new independent thread. to send mail which send mail to thousand of user and main thead with out any problem come to group page.
How i will make new thread in class.
thanks in advances.
for more info visit http://www.rameshsengani.in
new Thread(new Runnable() {
#Override
public void run() {
// do stuff here
}
}).start();
This is the accepted Java pre-1.5 way. You can take a look at the java.util.concurrent package and the executor framework.