This article for you to share the user login log and upload the server's specific implementation code, for your reference, the specific contents are as follows
The client runs on a server that provides UNIX services to users. Used to read and collect the user's up and down information on the server, and to perform paired collation and send it to the service-side rollup.
Specific implementation code:
1. Dmsserver.java
Package COM.DMS;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import Java.util.concurrent.BlockingQueue;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.LinkedBlockingQueue;
Import org.dom4j.Document;
Import org.dom4j.Element;
Import Org.dom4j.io.SAXReader; /** * DMS server, used to receive the * pairing log sent by each client and saved in local file * @author Administrator */public class Dmsserver {//attribute definition//used to receive customer
ServerSocket private ServerSocket server with end-connected server;
The thread pool used to manage threads that handle client requests private Executorservice ThreadPool;
Save all clients sent over the matching log files private file serverlogfile; Message Queuing private blockingqueue<string> messageQueue = new linkedblockingqueue<String> ();
Public Dmsserver () throws exception{try {System.out.println ("service is initializing ...");
1 Parse configuration file server-config.xml map<string,string> config = loadconfig ();
2 initializes the property Init (config) according to the configuration file content;
SYSTEM.OUT.PRINTLN ("server-side initialization complete ...");
catch (Exception e) {System.out.println ("Initialize service side failed!");
Throw e;
}/** * Constructor initializes the first step, parsing the configuration file * @return The returned map holds the * Every piece of content in the configuration file, where key: the name of the tag, * value is the text in the middle of the label * @throws Exception/private map<string,string> Loadconfig () throws exception{try {Saxreader R
Eader = new Saxreader ();
Document doc = Reader.read (new File ("Server-config.xml"));
Element root = Doc.getrootelement ();
map<string,string> config = new hashmap<string,string> (); * * Get all the child tags in the <config> label * and the name of each child label as key, the middle of the * text as value into the map set * * * List<elem ent> list = root.Elements ();
for (Element e:list) {String key = E.getname ();
String value = E.gettexttrim ();
Config.put (key, value);
} return config;
catch (Exception e) {System.out.println ("Parse configuration file Exception!");
E.printstacktrace ();
Throw e; The/** * constructor initializes the second step, initializing the property according to the configuration item * @param config * @throws Exception/private void init (map<str ing,string> config) throws exception{/* with <logrecfile> initialization properties in configuration file: Serverlogfile * Using <thre in configuration file Adsum> Initialization properties: ThreadPool, this creates a fixed size thread pool. This value is the number of thread pool threads * Using the <serverport> initialization properties in the configuration file: Server, where this value is ServerSocket service port/this.server = new Serversocke
T (Integer.parseint (Config.get ("ServerPort"));
This.serverlogfile = new File (Config.get ("Logrecfile"));
This.threadpool = Executors.newfixedthreadpool (Integer.parseint (Config.get ("threadsum"));
/** * Service-side start work method * @throws Exception * * public void Start () throws exception{/* Implementation requirements: * First start a separate thread, to run the Saveloghandler * This task, to save all matching log
* Then start to loop on the server port, once a client is connected, * Instantiate a clienthander, and then hand the task to the thread pool * to allocate threads to handle the interaction with the client.
* * * */try {System.out.println ("service side starts work ...");
Saveloghandler slh=new Saveloghandler ();
New Thread (SLH). Start ();
while (true) {Socket socket=server.accept ();
Threadpool.execute (new ClientHandler (socket));
} catch (Exception e) {e.printstacktrace ();
Throw e;
} public static void Main (string[] args) {try {dmsserver server = new Dmsserver ();
Server.start ();
catch (Exception e) {System.out.println ("Start server failed!"); }/** * This thread is responsible for removing each pairing log from the message queue, * to the serverlogfile file * @author Administrator */Private class Save
Loghandler implements runnable{public void run () {PrintWriter PW = null;
try { PW = new PrintWriter (new FileOutputStream (serverlogfile,true));
while (true) {if (Messagequeue.size () >0) {pw.println (Messagequeue.poll ());
}else{Pw.flush ();
Thread.Sleep (500);
A catch (Exception e) {e.printstacktrace ());
} finally{if (pw!= null) {pw.close (); /** * Process a specified client request * @author Administrator */private class ClientHandler Impleme
NTS runnable{private socket socket;
Public ClientHandler (socket socket) {this.socket = socket; public void Run () {* * * * thought: * First Receive all the pairing logs sent by the client, * until read to "over", and then save the matching * log to this
In the file and reply to the client * "OK" * Execute step: * 1: Create output stream via socket to send response to client * 2: Create input stream via socket, read client send * Come over the log * 3: Loop read the client sent over each line of string, and * First judge whether the string "over"If not, then a pair of pairs log, then save to the local file, if, * then stop reading.
* 4: After the successful reading of all the log reply to the client "OK" * * * printwriter PW = null; try {//1 pw = new PrintWriter (New OutputStreamWriter (Socket.getoutputstream (), UT
F-8 ")); 2 BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream (), "
UTF-8 "));
3 String message = NULL;
while (message = Br.readline ())!=null) {if (' over '. Equals (message)) {break;
///write the log to the file save Messagequeue.offer (message);
}//4 pw.println ("OK");
Pw.flush ();
catch (Exception e) {e.printstacktrace ();
Pw.println ("ERROR");
Pw.flush ();
finally{try {//disconnect from Client socket.close resources (); catch (IOExceptione) {e.printstacktrace (); }
}
}
}
}
2. Dmsclient.java
Package COM.DMS;
Import Java.io.BufferedReader;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.io.RandomAccessFile;
Import Java.net.Socket;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import Java.util.Map.Entry;
Import Java.util.Set;
Import org.dom4j.Document;
Import org.dom4j.Element;
Import Org.dom4j.io.SAXReader;
Import Com.dms.bo.LogData;
Import Com.dms.bo.LogRec;
/** * This client runs on a server that provides UNIX services to users.
* Used to read and collect the user's upper and lower line information on the server, and * to be paired and sent to the service-side rollup. * @author Administrator */public class Dmsclient {//attribute definition//First step: Parse Log Required properties//unix System log file Private file Logfil
E
Save the file to resolve the blog private file textlogfile;
Bookmark files private file lastpositionfile;
The number of entries per parse log is private int batch;
Step two: Matching log required attributes//save pair log files private file logrecfile;
Save the file with the mismatched logs private file loginlogfile;
Step three: The attributes required to send logs Service-side address private String serverhost;
Server port private int serverport; /** * Construction method, used to initialize client * @throws Exception/Public dmsclient () throws exception{try {//1 parse config file conf
Ig.xml map<string,string> config = loadconfig ();
Piling System.out.println (config);
2 initializes the property Init (config) according to the configuration file content;
catch (Exception e) {System.out.println ("Initialization failed!");
Throw e; The/** * constructor initializes the second step, based on the configuration item initialization property * @param config * @throws Exception/private void init (map<string,
string> config) throws exception{try {logFile = new File (Config.get ("LogFile"));
Textlogfile = new File (Config.get ("Textlogfile"));
Lastpositionfile = new File (Config.get ("Lastpositionfile"));
Batch = Integer.parseint (Config.get ("batch"));
Logrecfile = new File (Config.get ("Logrecfile")); LoginloGfile = new File (Config.get ("Loginlogfile"));
ServerHost = Config.get ("ServerHost");
ServerPort = Integer.parseint (Config.get ("ServerPort"));
catch (Exception e) {System.out.println ("Initialize property failed!");
E.printstacktrace ();
Throw e; }/** * Constructor initializes the first step, parsing the configuration file * @return The returned map holds the * each piece of content in the configuration file, where key: the name of the tag, * value is the middle of the label Text * @throws Exception/private map<string,string> Loadconfig () throws exception{try {Saxread
ER reader = new saxreader ();
Document doc = Reader.read (new File ("Config.xml"));
Element root = Doc.getrootelement ();
map<string,string> config = new hashmap<string,string> (); * * Get all the child tags in the <config> label * and the name of each child label as key, the middle of the * text as value into the map set * * * List<elem
ent> list = Root.elements (); for (Element e:list) {String key = e.GetName ();
String value = E.gettexttrim ();
Config.put (key, value);
} return config;
catch (Exception e) {System.out.println ("Parse configuration file Exception!");
E.printstacktrace ();
Throw e; /** * Client started working method * Loop Execution Three steps: * 1: Parse log * 2: Pair log * 3: Send log/public void start () {Parselog
S ();
Matchlogs ();
Sendlogs (); while (true) {////parse Log//if (!parselogs ()) {//continue;//}////pair Log//if (!matchlogs ())
{//continue;//}////Send Log//Sendlogs ();
/** * Step three: Send log * @return true: Send successfully * false: Send failed/private Boolean sendlogs () {/*
* Implementation of the idea: * logrecfile files in all pairs of log read * and then connected to the server and send the past, if the service-side * All received, you can delete the file, said sent * finished. * Implementation steps: * 1:logrecfile file must exist * 2: Read all pairing logs and deposit in a set * wait to send * 3: Connect via Socket * 4: Chuang Build Output Stream * 5: Sequentially sends all pairing logs to the service side * 6: Send a single string "Over" to represent all daysLog * All sent * 7: Create input stream * 8: Read the response string sent back by the server * 9: If the response string is "OK", indicating that the server is normal * Receive all the logs, then the log can be
Recfile * File Deletion and return True indicates that the send completed.
* * * */SOCKET socket = NULL;
try {//1 if (!logrecfile.exists ()) {System.out.println (logrecfile+ "does not exist!");
return false;
}//2 list<string> matches = Ioutil.loadlogrec (logrecfile);
3 socket = new socket (serverhost,serverport);
4 PrintWriter pw = new PrintWriter (New OutputStreamWriter (Socket.getoutputstream (), "UTF-8"
)
);
5 for (String log:matches) {pw.println (log);
}//6 pw.println ("over");
Pw.flush ();
7 BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream (), "UTF-8"
)
); 8 String response = Br.readlINE ();
9 if ("OK". Equals (response)) {logrecfile.delete ();
return true;
}else{System.out.println ("Send log failed!");
return false;
The catch (Exception e) {System.out.println ("Failed to send log!");
E.printstacktrace ();
finally{if (socket!= null) {try {socket.close ();
catch (IOException e) {e.printstacktrace ();
}} return false;
/** * Second step: Pairing log * @return true: Paired successfully * false: Pairing failed/private Boolean matchlogs () {/*
* Implementation of the idea: * will be the first step to parse the new log, and last for the matching success * Log all read out, and then according to user, * pid is the same, type one is 7, one is 8 to match.
* As long as you can find a type of 8, you can always find a * can be paired with the login log.
* * Implementation steps: * 1: the necessary judgment * 1.1:logrecfile exists, there is no longer * to carry out new matching work, to avoid coverage.
* 1.2:textlogfile file must exist. * 2: Read textlogfile to read the log out, and * into the collection. (Several Logdata instances) * 3: If the Loginlogfile file exists, it means * There is a last unsuccessful pair of logs, also read * out into the collection waiting to be paired together * 4: Paired work * 4.1: Create a collection to hold all pairing logs * 4.2: Create two maps to save login logs and Logout separately
log * 4.3: Iterate through all the logs to be paired, according to login and logout * into two maps, * where Key:user,pid * Value:logdata instance * 4.4: Traverse the Logout map and locate the corresponding login log in the map according to each log key *, and * Save the pairing log with a Logrec instance, then * deposit the pairing log collection. and delete the login log in the pairing log * from the login map.
So * login map should be left with no matching.
* 5: Write pairing log to Logrecfile * 6: Write all mismatched logs to Loginlogfile * 7: Delete textlogfile file * 8: Returns True, means pairing is complete *
*/try {//1//1.1 if (logrecfile.exists ()) {return true;
}//1.2 if (!textlogfile.exists ()) {System.out.println (textlogfile+ "does not exist!");
return false;
}//2 list<logdata> List = Ioutil.loadlogdata (textlogfile);
3 if (loginlogfile.exists ()) {List.addall (Ioutil.loadlogdata (Loginlogfile) );
}//4//4.1 list<logrec> matches = new arraylist<logrec> ();
4.2 map<string,logdata> Loginmap = new hashmap<string,logdata> ();
map<string,logdata> Logoutmap = new hashmap<string,logdata> ();
4.3 for (logdata logdata:list) {String key = Logdata.getuser () + "," + logdata.getpid ();
if (Logdata.gettype () ==logdata.type_login) {loginmap.put (key, Logdata);
}else if (Logdata.gettype () ==logdata.type_logout) {logoutmap.put (key, Logdata);
}//4.4 set<entry<string,logdata>> EntrySet = Logoutmap.entryset ();
for (entry<string,logdata> e:entryset) {Logdata logout = E.getvalue ();
Logdata login = Loginmap.remove (E.getkey ());
Logrec Logrec = new Logrec (login,logout);
Matches.add (LOGREC);
} 5 ioutil.savecollection (matches, logrecfile);
6 ioutil.savecollection (Loginmap.values (), loginlogfile);
7 Textlogfile.delete ();
8 return true;
catch (Exception e) {System.out.println ("Paired log failed!");
E.printstacktrace ();
return false; /** * First step: Parse log * @return true: Parse succeeded * false: Parse failed/private Boolean parselogs () {/* * implementation Train of thought: * Read the batch log, then parse out the * 5 information in each log, and eventually compose a string to the * behavior unit, write to the Textlogfile file * * Implementation steps: * 1:
Necessary Judgment Work * 1.1: In order to avoid the parsing of the log has not been used, and * The first step is repeated to cause before the log is covered * problem, here needs to be judged, if the log file is saved after resolution exists, then the first step is no longer executed.
* The log file is deleted after the second step is paired.
* 1.2:logfile file must exist (wtmpx file) * 1.3: whether there are still logs can parse * 2: Create Randomaccessfile to read logfile * 3: Move the pointer to the last read position, prepare * Start a new parsing work * 4: Parsing work * 4.1: Create a list collection for each log that is parsed (logdata instance) * 4.2: Loop batch times, solutionAnalysis of * 5 items in each log (user,pid,type,time,host) * and save with a logdata instance, then deposit the Logdata instance into the collection * 5: All the logs in the collection To be saved in a unit of Textlogfile * 6: Save Bookmark Info * 7: Return TRUE to indicate completion * */Randomaccessfile RAF = NULL
;
try {//1//1.1 if (textlogfile.exists ()) {return true;
}//1.2 if (!logfile.exists ()) {System.out.println (logfile+ "does not exist!");
return false;
//1.3 Long lastposition = Haslogs ();
Piling//SYSTEM.OUT.PRINTLN (//"lastposition:" +lastposition//);
if (lastposition<0) {System.out.println ("No log can parse!");
return false;
}//2 RAF = new Randomaccessfile (LogFile, "R");
3 Raf.seek (lastposition);
4 list<logdata> List = new arraylist<logdata> (); for (int i=0;i<batch;i++) {//before each parse to determine if there is a log to parse if (logfile.lengtH ()-lastposition <logdata.log_length) {break;
}//Parse USER Raf.seek (lastposition+logdata.user_offset);
String user = ioutil.readstring (RAF, Logdata.user_length). Trim ();
Analytic PID Raf.seek (lastposition+logdata.pid_offset);
int pid = Raf.readint ();
Parse TYPE Raf.seek (lastposition+logdata.type_offset);
Short type = Raf.readshort ();
Parse Time Raf.seek (Lastposition+logdata.time_offset);
int time = Raf.readint ();
Parsing HOST Raf.seek (lastposition+logdata.host_offset);
String host = ioutil.readstring (RAF, Logdata.host_length). Trim ();
Logdata log = new Logdata (user, PID, type, time, host);
List.add (log);
Piling//SYSTEM.OUT.PRINTLN (log); When you have finished parsing a log, update LastpositiOn lastposition = Raf.getfilepointer ();
}//5 ioutil.savecollection (list, textlogfile);
6 Save bookmark File Ioutil.savelong (lastposition, lastpositionfile);
7 return true;
catch (Exception e) {System.out.println ("Parse log failed!");
E.printstacktrace ();
} finally{if (RAF!= null) {try {raf.close ();
catch (IOException e) {e.printstacktrace ();
}} return false;
/** * The first step of parsing the log in a link, * According to the location of the bookmark file to determine whether there is a * log can be resolved, if so, then the last position * returned, if not then return 1.
* @return/Private Long haslogs () {try {* * * * * If Lastpositionfile does not exist, the * has never been resolved, then the beginning of the resolution can be
*/if (!lastpositionfile.exists ()) {return 0;
Long lastposition = Ioutil.readlong (lastpositionfile); if (Logfile.length ()-lastposition >=logdata.log_length) {return lastposition;
} catch (Exception e) {e.printstacktrace ();
} return-1;
public static void Main (string[] args) {try {dmsclient client = new Dmsclient ();
Client.start ();
catch (Exception e) {System.out.println ("Client run failed!"); }
}
}
3. Ioutil.java
Package COM.DMS;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import Java.io.RandomAccessFile;
Import java.util.ArrayList;
Import java.util.Collection;
Import java.util.List;
Import Com.dms.bo.LogData; /** * This class is a tool class that is responsible for client IO operations * @author Administrator */public class Ioutil {/** * reads each line of string from a given file (pairing log) * and deposits A collection returns * @param file * @return * @throws Exception/public static list<string> Loadlogrec (file fil
E) throws exception{bufferedreader br = null;
try {br = new BufferedReader (new InputStreamReader (new FileInputStream) (file
)
)
);
list<string> list = new arraylist<string> ();
String line = null;
while (line = Br.readline ())!=null) {List.add (line);
} return list; catch (Exception e) {E.printstackTrace ();
Throw e;
} finally{if (br!= null) {br.close ();
}}/** * Reads each pairing log from a given file and deposits it in a collection and returns it. * @param file * @return * @throws Exception/public static list<logdata> loadlogdata (file file) throws
exception{BufferedReader br = null;
try {br = new BufferedReader (new InputStreamReader (new FileInputStream) (file
)
)
);
list<logdata> list = new arraylist<logdata> ();
String line = null;
while (line = Br.readline ())!=null} {logdata logdata = new Logdata (line);
List.add (Logdata);
} return list;
catch (Exception e) {e.printstacktrace ();
Throw e;
} finally{if (br!=null) {br.close ();
/** * Writes the specified Long value as a string to the first line of the given file * @param l * @param file * @throws Exception * * public static void Savelong (long Lon,file File) throws exception{printwriter pw = null;
try {pw = new PrintWriter (file);
Pw.println (LON);
catch (Exception e) {e.printstacktrace ();
Throw e;
} finally{if (pw!= null) {pw.close ();
/** * Writes the String * returned by the ToString method of each element in the collection to the specified file in the behavior unit. * @param c * @param file * @throws Exception/public static void Savecollection (Collection
C,file File) throws exception{printwriter pw = null;
try {pw = new PrintWriter (file);
for (Object o:c) {pw.println (o);
} catch (Exception e) {e.printstacktrace ();
Throw e;
} finally{if (pw!= null) {pw.close ();
}}/** * Reads length bytes from the given Randomaccessfile current position and converts to string returns * @param RAF * @param length * @return * @throws Exception/public static String readString (randomaccessfile raf,int length) thro WS Exception{try {byte[] data = new Byte[length];
Raf.read (data);
return new String (data, "iso8859-1");
catch (Exception e) {e.printstacktrace ();
Throw e;
}/** * Reads the first line of string from a given file and converts its * to a long value and returns * @param file * @return * @throws Exception * *
public static long Readlong (file file) throws exception{BufferedReader br = null;
try {br = new BufferedReader (new InputStreamReader (new FileInputStream) (file
)
)
);
String line = Br.readline ();
return Long.parselong (line);
catch (Exception e) {e.printstacktrace ();
Throw e;
} finally{if (br!= null) {br.close (); }
}
}
}
4. Config.xml
<?xml version= "1.0" encoding= "UTF-8"?>
<config>
<!--Unix System log file name-->
<logfile> Wtmpx</logfile>
<!--Save resolution of the filename-->
<textlogfile>log.txt</textlogfile>
< !--bookmark filename-->
<lastpositionfile>last-position.txt</lastpositionfile>
<!--the number of entries per log resolved-- >
<batch>10</batch>
<!--pairing log file name-->
<logrecfile>logrec.txt</ Logrecfile>
<!--not paired log file name-->
<loginlogfile>login.txt</loginlogfile>
<!-- Service-side address-->
<serverhost>localhost</serverhost>
<!--service port-->
<serverport >8088</serverport>
</config>
5. Server-config.xml
<?xml version= "1.0" encoding= "UTF-8"?>
<config>
<!--server to save the file name of the pairing log file-->
< Logrecfile>server-logs.txt</logrecfile>
<!--thread pool threads number-->
<threadsum>30</ Threadsum>
<!--service port-->
<serverport>8088</serverport>
</config>
The above is the entire content of this article, I hope to help you learn.