Implementation of Java timed task using method ring letter chat record synchronization and timed deletion

Source: Internet
Author: User
Tags constant json


Timed Task code:

public class Chathistorytimerlistener implements Servletcontextlistener {
String chaturl= "Http://a1.easemob.com/***/********/chatmessages";
Private Chathistoryservice Chservice;
Private Timer Timer=null;
Private static final Long Period_day = 24 * 60 * 60 * 1000;
Private static final long period_day = 1000;
@Override
public void contextdestroyed (Servletcontextevent arg0) {

}

@Override
public void contextinitialized (Servletcontextevent event) {
Timer=new Timer ();
Webapplicationcontext ApplicationContext = Webapplicationcontextutils.getwebapplicationcontext ( Event.getservletcontext ());
This.chservice= (Chathistoryservice) Applicationcontext.getbean ("Chservice");
Calendar calendar = Calendar.getinstance ();
Calendar.set (Calendar.hour_of_day, 1); 1 o'clock in the morning
Calendar.set (calendar.minute,0);
Calendar.set (Calendar.second, 0);
Date Date=calendar.gettime ();
Event.getservletcontext (). log ("Ring Letter----------------Timer has been started. ") ;
TimerTask task=new TimerTask () {
@Override
public void Run () {
String tokenurl= "Http://a1.easemob.com/***/*****/token";
Map<string,string>parammap=new hashmap<string,string> ();
Parammap.put ("Grant_type", "client_credentials");
Parammap.put ("client_id", config.hxclient_id);
Parammap.put ("Client_secret", Config.hxclient_secret);
Map<string, Object>tokenmap=jsontools.jsonstrtomap (Httptools.post (Tokenurl,parammap));
System.out.println (Calendar.get (Calendar.minute));
List<map<string,string>>headerlist=new arraylist<map<string,string>> ();
Map<string,string>header=new hashmap<string, string> ();
Map<string,string>header2=new hashmap<string, string> ();
Header.put ("Headername", "Authorization");
Header.put ("Headervalue", "Bearer" +tokenmap.get ("Access_token"). toString ());
Header2.put ("Headername", "Content-type");
Header2.put ("Headervalue", "Application/json");
Headerlist.add (header);
Boolean isrun=true;
String pagram= "";
Here is the time to determine the last message after the last synchronization was completed, followed by Time data
Ql=select * where timestamp<1403164734226 and timestamp>1403166586000
Timestamp time=chservice.getnewtimesynchronous ();
if (Chktools.isnotnull (time)) {
chaturl=chaturl+ "?ql=select+*+where+timestamp>" +time.gettime () + "&limit=100";
}else{
chaturl=chaturl+ "limit=100";
}
while (Isrun) {
String Json=httptools.getsetheader (Chaturl+pagram, headerlist);
if (Chktools.isnull (JSON)) {
Isrun=false;
Break
}
Jsonobject O=json.parseobject (JSON);
if (Chktools.isnotnull (O.get ("cursor"))) {
Pagram= "&cursor=" +o.get ("cursor"). toString ();
}else{
Isrun=false;
}
Chservice.synchronouschat (O,event.getservletcontext (). Getrealpath ("/"));
Starting here, business data is shared in the following code

try {
Thread.Sleep (10000);
System.out.println ("Wait 1000 milliseconds to execute next cycle");
catch (Interruptedexception e) {
E.printstacktrace ();
}
Delete the local server's cached file, the file has been saved to seven cows
File File=new file (Event.getservletcontext (). Getrealpath ("/") + "Downtem");

DeleteFile (file);
}

Scheduled deletion of three days before the chat record
Chservice.deletetimeagohistory ();

}
};
Timer.schedule (task, date,period_day);
Event.getservletcontext (). log ("Chat log--------have added the Task Scheduler table. " ) ;
}
Using the spring implementation instantiation
Public Chathistoryservice Getchservice () {
return chservice;
}
public void Setchservice (Chathistoryservice chservice) {
This.chservice = Chservice;
}

private void DeleteFile (file file) {
if (File.isdirectory ()) {
file[] files = file.listfiles ();
for (int i=0; i<files.length; i++) {
DeleteFile (Files[i]);
}
}
File.delete ();
}
}
Business code

public void Synchronouschat (Jsonobject o, String filepath) {

Jsonarray e = (jsonarray) o.get ("entities");
if (e.size () > 0) {
list<b_chat_history> list = new arraylist<b_chat_history> ();
for (int i = 0; i < e.size (); i++) {
B_chat_history bchistory = new B_chat_history ();
Jsonobject s = e.getjsonobject (i);
String from = s.getstring (' from ');
String to = s.getstring ("to");
Long timestamp = Long.parselong (s.getstring ("timestamp"));
Jsonobject p = (jsonobject) s.get ("payload");
Jsonarray bodies = (Jsonarray) p.get ("bodies");
Jsonobject B = bodies.getjsonobject (0);
"MSG": "Hahaha", "type":
"TXT" "type": "Video",
Start assigning values
Bchistory.setfrom_phone (from);
Bchistory.setto_phone (to);
Bchistory.setfrom_user (GetUserName (from));
Bchistory.setto_user (To) (GetUserName);

Bchistory.settimestamp (New Java.sql.Timestamp (Timestamp));
Switch (b.getstring ("type")) {
Case "TXT":
Bchistory.setmsg (b.getstring ("MSG"). Replace ("\ n", ""));
Bchistory.settype ("txt");
Bchistory.setlength (0);
Break
Case "Video":
Bchistory.settype ("video");
String Videokey = "Video_" + New Date (). GetTime () + ". mp4";
try {
String file = httpdownutil.downloadnet (filepath,
b.getstring ("url"), "mp4");
try {
Qiniuuplodutil.upload (file, Videokey);
catch (IOException E1) {
E1.printstacktrace ();
}
catch (Malformedurlexception E1) {
E1.printstacktrace ();
}
Bchistory.seturl (Constant.qiniu_url_web + videokey);
String Thumbkey = "Video_" + New Date (). GetTime () + ". png";
try {
String file = httpdownutil.downloadnet (filepath,
B.getstring ("thumb"), "PNG");
try {
Qiniuuplodutil.upload (file, Thumbkey);
catch (IOException E1) {
E1.printstacktrace ();
}
catch (Malformedurlexception E1) {
E1.printstacktrace ();
}
Bchistory.setthumb (Constant.qiniu_url_web + thumbkey);
Bchistory.setlength (0);
Break
Case "IMG":
Bchistory.settype ("img");
String Imgkey = "Img_" + New Date (). GetTime () + ". png";
try {
String file = httpdownutil.downloadnet (filepath,
b.getstring ("url"), "PNG");
try {
Qiniuuplodutil.upload (file, Imgkey);
catch (IOException E1) {
E1.printstacktrace ();
}
catch (Malformedurlexception E1) {
E1.printstacktrace ();
}
Bchistory.seturl (Constant.qiniu_url_web + imgkey);
Bchistory.setlength (0);
Break
Case "Audio":
Bchistory.settype ("audio");
String Audiokey = "Audio_" + New Date (). GetTime () + ". Amr";
try {
String file = httpdownutil.downloadnet (filepath,
b.getstring ("url"), "Amr");
try {
Qiniuuplodutil.upload (file, Audiokey);
catch (IOException E1) {
E1.printstacktrace ();
}
catch (Malformedurlexception E1) {
E1.printstacktrace ();
}
"Length": 10, voice often seconds
Bchistory.setlength (Integer.parseint (b.getstring ("Length"));
Bchistory.seturl (Constant.qiniu_url_web + audiokey);
Break
}
List.add (bchistory);
}
/**
* Use SPRINGJDBC to perform bulk save here
*/
try {
Jt.batchupdate (
"INSERT into B_chat_history (id,from_phone,from_user,to_phone,to_user,type,msg,url,thumb,length,timestamp) value (?) ,?,?,?,?,?,?,?,?,?,?)",
New BatchPreparedStatementSetter () {
public void Setvalues (preparedstatement ps, int i)
Throws SQLException {
Ps.setstring (1, Uuid.randomuuid (). toString ());//ID's value
Ps.setstring (2, List.get (i). Getfrom_phone ());
Ps.setstring (3, List.get (i). Getfrom_user ());
Ps.setstring (4, List.get (i). Getto_phone ());
Ps.setstring (5, List.get (i). Getto_user ());
Ps.setstring (6, List.get (i). GetType ());
Ps.setstring (7, List.get (i). getmsg ());
Ps.setstring (8, List.get (i). GETURL ());
Ps.setstring (9, List.get (i). Getthumb ());
Ps.setint (10,list.get (i). GetLength ());
Ps.settimestamp (one, List.get (i). Gettimestamp ());
}

public int getbatchsize () {
return List.size ();
}
});
catch (Exception E2) {
SYSTEM.OUT.PRINTLN ("There may be data anomalies, synchronizing partial data exceptions");
E2.printstacktrace ();
}
}

}
OK, the results of the final implementation are as follows

Uploaded to seven cow files: Voice, video, picture

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.