Vous êtes sur la page 1sur 48

JAVA NETWORK MONITOR

1. INTRODUCTION
1.1 ABOUT THE PROJECT

The Java Network Monitor (JNM) is an open source Java application which allows you to define monitors which can poll network services at defined intervals and execute user-definable actions when the service status changes.

Instructions

Start the program by either double-clicking the JNM.jar file or entering the following on the command line: java -jar JNM.jar. The main screen should appear. You must now configure your monitors. Select Monitor -> Add Monitor... from the menu.

The Monitor dialog will appear in window like Appendix A(2). You can specify a name and a delay for all monitors. Individual monitor implementations provide different editors for their required properties. Selecting a different monitor type from the combo box will cause the UI in the
1|Page

JAVA NETWORK MONITOR General tab to change. Note: Selecting a new monitor type will remove all changes you have made in the General tab!

Fill in the fields of the monitor dialog. The example below shows how to configure an HTTP monitor. You can specify the URL which will be requested, the timeout, the request method (GET/POST/HEAD), the regular expression to use to verify the response, as well as basic authentication information if necessary.

When you click OK it will add your monitor to the main screen's monitor table. The monitor table displays each monitor's name, its current activity and its current state. The color of the state cell will change depending on the state.

2|Page

JAVA NETWORK MONITOR

You can change a monitor's properties by right-clicking the monitor's row. You can also start and stop individual monitors, remove a monitor, execute a monitor immediately, and see the last request and response using this pop-up menu.

3|Page

JAVA NETWORK MONITOR You can configure actions to be triggered when a monitor enters a particular state. First you must configure one or more actions by selecting Monitor -> Actions... from the menu.

An action manager dialog will appear. Using this dialog you can add, edit and remove actions from your action list.

4|Page

JAVA NETWORK MONITOR Configuring an action is very similar to configuring a monitor. Fill in the necessary information in the General panel and click OK to save your changes.

Once you have created one or more actions you can assign them to monitors. When viewing the monitor's properties, select the Actions tab. There is a combo box with a list of all possible states. Selecting a state will show all actions which are triggered when the monitor is in that state. Note: actions will currently be triggered at every execution of the monitor, regardless if state has changed! You can add or remove actions from the state's action list with the add and remove button.

5|Page

JAVA NETWORK MONITOR

You can save your current configuration at any time. When you quit JNM you will be prompted to save your configuration if any changes have been made. Note: it is advised that for the moment you save your configuration manually on a regular basis to not lose any changes!

Monitors - JNM currently includes two monitor implementations

TCP Monitor Send a single raw payload over TCP to a server. Compares the resulting response against a user-defined regular expression. HTTP Monitor Invoke a particular URL. Includes support for Basic Authentication. Compares the resulting response against a user-defined regular expression.

6|Page

JAVA NETWORK MONITOR More monitors will be added in the future.

You can also create your own monitor by extending the com.anthonyeden.jnm.Monitor abstract base class and implementing the execute() method. The execute() method is called at the end of each wait interval. Your implementation of the execute() method can call setState() at any time to update the current state of the server which is being polled. Available states are found in the MonitorState class and include:

MonitorState.OK MonitorState.DOWN MonitorState.ERROR implementations must be accompanied

MonitorState.FAILED MonitorState.TIMEOUT MonitorState.NOT_TESTED by a class which implements the

Monitor

com.anthonyeden.jnm.MonitorEditor interface. Implementations of this class are used to provide a user-interface for editing your monitor's properties.

To use your monitor implementation, include it in JNM's application classpath and add an entry to the jnm.xml configuration file:

<register-monitor>My Monitor</name> <classname>com.mycompany.MyMonitor</classname> <editorclass>com.com.mycompany.MyMonitorEditor</editorclass> </register-monitor>

7|Page

JAVA NETWORK MONITOR Actions

When a monitor enters a particular state one or more actions can be triggered. Currently JNM includes the following actions:

HTTP Request Action Execute a specific URL. Includes support for basic authentication.

Additional actions can be created a similar fashion as monitors. You must create a class which extends from com.anthonyeden.jnm.Action, implement the execute(Monitor monitor) method, implement the com.anthonyeden.jnm.ActionEditor interface, and provide an entry in the jnm.xml configuration file:

<register-action> <name>My Action</name> <classname>com.mycompany.MyAction</classname> <editorclass>com.mycompany.MyActionEditor</editorclass> </register-action>

8|Page

JAVA NETWORK MONITOR

1.2

ORGANIZATION PROFILE
PSG College of Arts & Science (PSGCAS), at the industrial city of Coimbatore,

Tamilnadu, is a major contributor to the development of the country and the world in various spheres. This colossus in the field of higher education is the brainchild of the PSG & Sons' Charities Trust. The Trust was founded on 25th January 1926, with a capital of Rs.2,01,116/- by the four philanthropic sons of Sri.P.S.Govindaswamy Naidu (1856-1918), and a memorable chapter was written in the history of Coimbatore. The founder's vision............. Let there be charity so that other people may share my family's prosperity... - Sri P.S. Govindaswamy Naidu In tune with the above words is the objective of the Trust, namely.. 'To serve society through development of education, industry and the needy and poor' These visionary words of the founder years ago, and the objectives of the Trust, are in compliance with the nouveau thoughts of 'networking of resources' of today. Hence, it is a clear indication that the various institutions under the Trust have had a long innings in the concept of 'networking'. Many educational institutions have been established under the PSG & Son's Charities Trust. One among them is the PSG College of Arts & Science. The genesis of the college is rather historical. The spirit of freedom of the country was sown in the college which was founded on 11-8-1947, with the crack of dawn of our Indian country's independence.

Since then, the college has directed all its developmental efforts in tune with the objectives of the Trust. These objectives have since been translated into the Quality Policy of PSG College of Arts & Science.
9|Page

JAVA NETWORK MONITOR

2. SYSTEM ANALYSIS
System study is the first stage of system development life cycle. This gives a clear picture of what actually the physical system is. In practice, the system study is done in two phases. In the first phase, the preliminary survey of the system is done which helps in identifying the scope of the system. The second phase of the system study is more detailed and in-depth study in which the identification of users requirement and the limitations and problems of the present system are studied. Analysis involved a detailed study of the current system, leading to specifications of a system. Analysis is a detailed study of various operations performed by a system and their relationships within and outside the system. To describe the system study phase more analytically, we would say that system study phase passes through the following steps: Problem identification and project initiation Study on existing system Problem of existing system Defining a way for proposed system

10 | P a g e

JAVA NETWORK MONITOR

Problem identification and project initiation


Problem identification Two main activities Identification Prioritization and translation of need into a development schedule

Project initiation and planning Two activities Formal preliminary investigation of the problem at hand Presentations of reasons why system should or should not be developed by the organization

11 | P a g e

JAVA NETWORK MONITOR 2.1 EXISTING SYSTEM In an existing system if a network administrator wants to know about the details of the network (with Internet or without Internet) manually he should know these things with the help of some kind of network related software. It will be very tedious work to him in that environment. It leads to time consuming. Every individual parts of a networks performances (such as cables, processor, monitor etc) will be identified with the help of some individual software. Drawbacks of existing system Time consuming Cost expensive No effective management Expensive in soft wares

12 | P a g e

JAVA NETWORK MONITOR

2.2

PROPOSED SYSTEM

2.2.1 Defining the problem The organizations have setup the network of systems with different types of network related software to identify the network details. In order to identify the network details by individual software it needs so much of time to identify about everyone. This is time killing process and also makes risks on manual work.

2.2.2 Developing the solution strategies After I understood the problem of organization I come with the solution by implementing TCP and HTTP based network application in java to achieve our goal.

2.2.3 Outline of the proposed system The proposed system is designed to be simple to use, simple to understand and easy to implement and configure to fit the need the requirement. It is provided as an Application service provision thus offering low setup costs. The main objective of this project is, giving provision to both kinds of networks (based on TCP and HTTP) to know about the network details. Our project avoids manual work to be done to achieve our target. Instead of spending more money to get network details we can get all by this single software.

13 | P a g e

JAVA NETWORK MONITOR

3. SYSTEM SPECIFICATION
3.1 HARDWARE SPECIFICATION
Processor RAM HDD FDD Monitor Pointing device Keyboard : : : : : : : Intel core 2 duo CPU 2.00 GHz 2GB 160 GB 1.44 MB 15 color monitor with 16 million colors 2-button mouse or 3-button mouse 104 keys

3.2 SOFTWARE SPECIFICATION


Platform Language Used technique Toolkit needed : : : : Microsoft Windows XP Java Java swing JDK 1.6

14 | P a g e

JAVA NETWORK MONITOR

3.3

LANGUAGE SPECIFICATION

JAVA Java is an enhancement of language which supports Object Oriented Programming. It is a powerful tool for creating a system utility. It makes it possible to perform with the help of its prewritten header files, it is possible for the programmer to create separate class files for separate function in a project, this makes the project object oriented. This enables the project to run independently. Java is a versatile language for handling very large program. It is suitable for virtually a programming task including development of editors, compilers, databases, communication systems and any complex real time systems. Java began as a programming language to create programs for embedded systemsmicrocomputers found in consumer and industrial products.

JAVA FEATURES Some of the important features that make java such a powerful development tool are simple, Object-Oriented, Distributed, Interpreted, Robust, Architectural-neutral, Portable, Highperformance, multithreaded and Dynamic.

15 | P a g e

JAVA NETWORK MONITOR JFC SWING Swing is a new set of GUI components with a pluggable look and feel that are implements in 100% pure java, and based on the JDK 1.1 lightweight UI framework. pluggable look and feel lets you easily assign an OS specific look and feel or a uniform look and feel to your swing GUI components. Swing components include both 100% pure java versions of the 1.1 AWT component set, plus a rich set of higher level components. The complete set includes borders, buttons, checkboxes, combo boxes, icons, labels, lists, list boxes, menus, menu bars, menu items, popup menus, radio buttons, progress bars, scroll panes &view ports, scrollbars tabbed panes, tables, text areas, text components, text fields, trees and HTML viewers. Accessibility is built-in to swing components; all swing components implement the java accessibility API.

16 | P a g e

JAVA NETWORK MONITOR

4. SYSTEM DESIGN
4.1 SYSTEM FLOW DIAGRAM
MONITORS DECIDING HTTP OR TCP MONITOR ADDED

ADD MONITORS

PROVIDING MONITOR DETAILS

MONITOR ADDED (SAVED HERE)

MONITOR TABLE

DISPLAYING EACH ADDED MONITORS NAME, ACTIVITY AND STATE CHANGING PROPERTIES DONE

ACTIONS

ACTIONS DONE

ACTIONS.

ACTION ADDED

ACTION VIEWED

ALL MONITORS DATA SAVED

17 | P a g e

JAVA NETWORK MONITOR 4.2 DESIGN PROCESS System design is described as a process of planning a new business system to replace or to complement an existing system. The system design states how our system will meet the requirements identified during the system analysis. It goes through a logical and physical design 4.2.1 INPUT DESIGN The design decisions for handling input specify how data are accepted for computer processing. The goal of the input design is to make the data entering processes easier, logical and free from errors. The input screens forms the primary interface between user and software system. In this project our initial forms name is Java Network Monitor. Here we are adding the types of system monitors which we should monitor. After adding monitors we should give attributes of all monitors. In monitor properties window we give inputs as the properties. Based on those properties we can perform actions on our required monitors. 4.2.2 OUTPUT DESIGN Computer output is the most important and direct source of information to the user. Without quality output, the entire system may appear to be so unnecessary that users will avoid using it, possibly causing it to fail. Efficient, intelligible output design should improve the systems relationships with the user and help in decision making. In this project output window shows the status of all monitors those we want to monitor. Whenever we want we can add or remove monitors during output time also.

18 | P a g e

JAVA NETWORK MONITOR

5. TESTING AND IMPLEMENTATION


Testing is vital to the success of the system. System testing makes a logical assumption that if all the parts of system are correct, the goal will be successfully achieved. Inadequate testing or non-testing leads to error that may not appear until months later. This creates a time lag between the cost and appearance of the problem and the effect of the system errors on files and records and the appearance of the problem and effect of the system errors on files and records within the system. Hence the aim of the testing is to create bug free reliable and secured system. The implementation of the newly designed package is an important phase in adopting a successful new system. The implementation of the package involves testing, user training, acceptance and changeover. The objective of testing is to create bug free reliable and secured system. The implementation of the newly designed package in an important phase in adopting a successful new system. The implementation of the package involves testing, user training, acceptance and changeover. The objective of testing is to discover errors. To fulfill this objective a series of test step unit, integration, validation and system test were planned and executed. A program module may function perfectly in isolation but fail when interfaced with other modules. The approach is to test each entity with successively larger ones, up to the system test level. System testing of the following steps: 1. Program testing 2. String testing
19 | P a g e

JAVA NETWORK MONITOR 3. System testing 4. Unit testing 5. Integrate testing 6. Positive testing Program testing A program represents the logical elements or a system. For a program to run satisfactory, it must compile and test data correctly and tie in properly with other programs. Achieving an error-free program is the responsibility of the programmer. Program testing checks for two types odd errors: syntax and logic. When program is tested actual output is compared with the expected output. When there is a discrepancy, the sequence of instruction must be traced to determine the problem. Breaking the problem facilities the process down into self-contained portion, each of which can be checked at certain key points. String Testing Programs are invariably related to one another and interact in a total system. Each program is tested to see whether it conforms to related programs in the total system. Each portion of the system is tested against the entire module with both test and live date before the entire system is ready to be tested. System testing System testing involves two kinds of activities: integration testing and acceptance testing. Strategies for integrating software components in to a component in to a functioning

20 | P a g e

JAVA NETWORK MONITOR product include the bottom-up strategy, the top-down strategy and sandwich strategy. Acceptance testing involves planning and execution of the functional tests, performance tests, and the stress tests to verify that the implemented system satisfies its requirements. System testing does not test module wise, but the integration of each module in the system. System testing helps to find out the in discrepancies, between the original objectives of the system. Unit Testing In this testing, each module are individually tested and integrated to the overall system. Unit testing focuses verification efforts on the smallest unit of software design in the module. This is also known as module testing. The modules of the system are tested separately. This testing is carried out during the programming stage itself. In this testing step each module is found to working satisfactorily as regard to the expected output from the module. Unit testing makes heavy use of white-box testing techniques, exercising specific paths in a modules control structure to ensure complete coverage and maximum error detection. Unit testing comprises the set of tests performed by an individual programmer prior to integration of the unit in to larger system. A program unit is usually small enough that the programmer who developed it can test it in a great detail. In unit testing the modules are independent of one another are tested, the test data for unit testing should follow each condition and option this testing helps to find out the errors in coding and option. There are 4 categories of tests that can be evolved in the process as follows: 1. Functional tests 2. Performance tests 3. Stress tests
21 | P a g e

JAVA NETWORK MONITOR 4. Structure tests Functional Test Functional test cases involve exercising the code with nominal input values for which the expected results are shown. Performance Test Performance test determines the amount of execution time spent in the various parts of the unit, program throughput in the program unit. Stress Test Stress tests are those designed to intentionally to break the unit. The great deal of the systems limitations and strengths of the program by examining the manner in which a program unit breaks. Structure Test Structure tests are concerned with the exercising the internal logic of the program and traversing particular execution paths. White & Black Box Testing White Box Testing refers that the testing done would be done in full detail. Each and every step including the variable assignments will be checked out. This type of testing is called White Box Testing. Black Box Testing is concerned as a testing process at an overall process. The Functional, Performance and the Stress Tests are refers collectively as Black Box Testing, while Structure Testing is known as White Box Testing.

22 | P a g e

JAVA NETWORK MONITOR Integrate Testing After completing all the frames they are integrated to form the end result. The testing was done with sample data. The developed system has run successfully for this sample data. The need for integrated test is to find the overall system performance. The data and output the system has been verified and validated by running. Test data 1. Live data

2. Run with Test data The cased are developed using sample data. Specification testing also done for each condition or combination of conditions. Modular approach is applied for testing the system. Each module is tested independently and after interfacing the modules with the main menu. Run with live data The system is tested with the data of the old system for a particular period and verified the old reports. Positive Testing It is to make that the new systems do in fact process certain operation according to specifications.

23 | P a g e

JAVA NETWORK MONITOR

6. SYSTEM MAINTENANCE
The system maintenance is classified into two subcategories. These are as follows: Corrective maintenance Perfective maintenance Corrective maintenance The first maintenance activity occurs because it is unreasonable that software testing will uncover all latent errors in a large software system, during the user of this system, errors were encountered and reported to the developer. The process that includes the diagnosis and correction one or more errors. Perfective maintenance As the system is used, recommendations for new capabilities, modifications to existing functions and general enhancements are received from users. To satisfy request in this category, perfective maintenance is done.

24 | P a g e

JAVA NETWORK MONITOR

7. SCOPE FOR FURTHER ENHANCEMENT


The software has been developed in such a way that it can accept modifications for future development and further changes. The software is very user friendly and any changes can be done easily because software restructuring is carried out. The improvement form of the proposed system over existing system is given below: We can measure the network traffic between various systems Rather displaying all activities done in network, we can indicate conditions and attributes of system hardware and software configurations.

25 | P a g e

JAVA NETWORK MONITOR

8. CONCLUSION
The project entitled JAVA NETWORK MONITOR has completed on time and is found to be mush faster, reliable and user friendly than an existing system. The system working under all circumstances that may arise in the real environment. The system has been designed and developed step by step and tested successfully. The system results in quick retrieval of information that is very vital for the progress any organization. Cost is minimized. Burden of manual work is reduced. The system objectives specified in the required documents are believed to have satisfactorily met. Users with low knowledge on computers can easily operate this system as the system is menu driven. Due to transportation time of data the work of the organization will be slow in manual system which is completely eliminated. This project has helped us in learning and implementing various modern technologies to co-exist with the existing one.

26 | P a g e

JAVA NETWORK MONITOR

9. BIBLIOGRAPHY
BOOKS [1] Henry Lewis, System Analysis and Design, Tata McGraw Hill publication 1st edition [2] Keyar shash, Java programming, Tata McGraw Hill publication 2nd edition [3] R.S.Pressman, Software Engineering, Tata McGraw Hill publication 1st edition WEBSITES [1] http://www.javacoffeebreak.com [2] http://java.sun.com [3] http://www.softwaretrainingtutorials.com

27 | P a g e

JAVA NETWORK MONITOR

APPENDIX
All screen shots Initial window

28 | P a g e

JAVA NETWORK MONITOR Monitor adding window

29 | P a g e

JAVA NETWORK MONITOR Monitor adding - Finalized

30 | P a g e

JAVA NETWORK MONITOR Monitor property changing window

31 | P a g e

JAVA NETWORK MONITOR Properties window

32 | P a g e

JAVA NETWORK MONITOR Action selection window

33 | P a g e

JAVA NETWORK MONITOR Action window

34 | P a g e

JAVA NETWORK MONITOR Action adding window

35 | P a g e

JAVA NETWORK MONITOR Monitor state window

36 | P a g e

JAVA NETWORK MONITOR

HTTP MONITOR
package com.anthonyeden.jnm.monitor;

import java.io.InterruptedIOException; import java.net.URL; import java.net.URLEncoder; import java.net.ConnectException; import java.net.MalformedURLException; import java.util.Map; import java.util.HashMap;

import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; import org.apache.oro.text.regex.MalformedPatternException;

import com.anthonyeden.lib.log.Logger; import com.anthonyeden.lib.log.LogManager; import com.anthonyeden.lib.config.Configuration; import com.anthonyeden.lib.config.MutableConfiguration; import com.anthonyeden.lib.config.ConfigurationException;

import com.anthonyeden.jnm.Monitor; import com.anthonyeden.jnm.JNMRequest; import com.anthonyeden.jnm.JNMResponse; import com.anthonyeden.jnm.MonitorState; import com.anthonyeden.jnm.util.Utilities; import com.anthonyeden.jnm.util.HttpClient;

public class HttpMonitor extends Monitor{


37 | P a g e

JAVA NETWORK MONITOR

public HttpMonitor(){ compiler = new Perl5Compiler(); matcher = new Perl5Matcher(); matcher.setMultiline(true); } public URL getURL(){ return url; }

public void setURL(URL url){ log.debug("setURL(" + url + ")");

if(url == null){ throw new IllegalArgumentException("URL is required"); } this.url = url; setDefaultName(url.toString()); }

public void setURL(String url) throws MalformedURLException{ setURL(new URL(url)); } public String getMethod(){ return method; } public void setMethod(String method){ this.method = method; } public String getExpression(){ return expression;
38 | P a g e

JAVA NETWORK MONITOR }

public void setExpression(String expression) throws MalformedPatternException{ this.expression = expression; this.pattern = compiler.compile(expression); } public int getTimeout(){ return timeout; } public void setTimeout(int timeout){ this.timeout = timeout; } public void setTimeout(String timeout){ if(timeout != null){ setTimeout(Integer.parseInt(timeout)); } } public boolean isUseAuthentication(){ return useAuthentication; } public void setUseAuthentication(boolean useAuthentication){ log.debug("setUseAuthentication(" + useAuthentication + ")"); this.useAuthentication = useAuthentication; } public void setUseAuthentication(String useAuthentication){ setUseAuthentication("true".equalsIgnoreCase(useAuthentication)); } public String getUsername(){ return username; } public void setUsername(String username){
39 | P a g e

JAVA NETWORK MONITOR this.username = username; } public String getPassword(){ return password; } public void setPassword(char[] password){ setPassword(new String(password)); } public void setPassword(String password){ this.password = password; } public void execute(){ HttpClient client = new HttpClient(); client.setTimeout(getTimeout());

try{ String responseData = client.sendRequest(getURL(), getMethod(), getHeaders()); setLastRequest(new JNMRequest(client.getLastRequestData())); setLastResponse(new JNMResponse(responseData, System.currentTimeMillis())); } catch(InterruptedIOException e){ log.error("Interrupted IO exception caught"); setLastResponse(null); setState(MonitorState.TIMEOUT); return; } catch(ConnectException e){ log.error("Connection failed"); setLastResponse(null); setState(MonitorState.DOWN); return; } catch(Exception e){
40 | P a g e

JAVA NETWORK MONITOR log.error("Exception caught"); setLastResponse(null); logError(e); setState(MonitorState.ERROR); return; } if(test(getLastResponse())){ setState(MonitorState.OK); log.info(getURL() + " is OK"); } else { setState(MonitorState.FAILED); log.info(getURL() + " is FAILED"); } } protected void readConfiguration(Configuration configuration) throws ConfigurationException{ log.debug("Reading configuration");

try{ setURL(configuration.getChildValue("url")); setMethod(configuration.getChildValue("method", DEFAULT_METHOD)); setExpression(configuration.getChildValue("expression", DEFAULT_EXPRESSION)); setTimeout(configuration.getChildValue("timeout", Integer.toString(DEFAULT_TIMEOUT))); setUseAuthentication(configuration.getChildValue("useAuthentication")); setUsername(configuration.getChildValue("username")); setPassword(configuration.getChildValue("password")); } catch(Exception e){ throw new ConfigurationException(e); }
41 | P a g e

JAVA NETWORK MONITOR }

protected void writeConfiguration(MutableConfiguration configuration) throws ConfigurationException{ configuration.addChild("url", getURL().toString()); configuration.addChild("method", getMethod()); configuration.addChild("timeout", Integer.toString(getTimeout())); configuration.addChild("expression", getExpression()); configuration.addChild("useAuthentication", new Boolean(isUseAuthentication()).toString()); configuration.addChild("username", getUsername()); configuration.addChild("password", getPassword()); } protected boolean test(JNMResponse response){ log.debug("Testing response"); boolean result = matcher.contains(response.toString(), pattern); log.debug("Test complete: " + result); return result; } private Map getHeaders(){ HashMap headers = new HashMap(); if(useAuthentication){ headers.put("Authorization", getAuthorizationHeaderValue()); } return headers; } private String getAuthorizationHeaderValue(){ StringBuffer buffer = new StringBuffer(); buffer.append("Basic "); buffer.append(Utilities.base64Encode(username + ":" + password)); return buffer.toString();
42 | P a g e

JAVA NETWORK MONITOR } public static final String HTTP_VERSION = "HTTP/1.0"; public static final String DEFAULT_METHOD = "GET"; public static final int DEFAULT_PORT = 80; public static final String DEFAULT_EXPRESSION = ""; public static final int DEFAULT_TIMEOUT = 30000; private static final Logger log = LogManager.getLogger(HttpMonitor.class.getName()); private Perl5Compiler compiler; private Perl5Matcher matcher; private Pattern pattern;

private URL url; private String method = DEFAULT_METHOD; private String expression = DEFAULT_EXPRESSION; private int timeout = DEFAULT_TIMEOUT; private boolean useAuthentication = false; private String username; private String password;

43 | P a g e

JAVA NETWORK MONITOR

TCP MONITOR
package com.anthonyeden.jnm.monitor; import java.io.InputStream; import java.io.OutputStream; import java.io.InterruptedIOException; import java.net.Socket; import java.net.ConnectException; import java.util.LinkedList;

import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; import org.apache.oro.text.regex.MalformedPatternException;

import com.anthonyeden.lib.log.Logger; import com.anthonyeden.lib.log.LogManager; import com.anthonyeden.lib.util.IOUtilities; import com.anthonyeden.lib.config.Configuration; import com.anthonyeden.lib.config.MutableConfiguration; import com.anthonyeden.lib.config.ConfigurationException;

import com.anthonyeden.jnm.Monitor; import com.anthonyeden.jnm.JNMRequest; import com.anthonyeden.jnm.JNMResponse; import com.anthonyeden.jnm.MonitorState; import com.anthonyeden.jnm.util.TCPClient; /** Monitor implementation which uses a tests a remote host using a TCP socket.@author Anthony Eden */ public class TCPMonitor extends Monitor{
44 | P a g e

JAVA NETWORK MONITOR public TCPMonitor(){ compiler = new Perl5Compiler(); matcher = new Perl5Matcher(); matcher.setMultiline(true); } public String getHost(){ return host; } public void setHost(String host){ log.debug("setHost(" + host + ")"); if(host == null){ return; } this.host = host; } public int getPort(){ return port; } public void setPort(int port){ log.debug("setPort(" + port + ")"); this.port = port; } public void setPort(String port){ if(port != null){ setPort(Integer.parseInt(port)); } } public int getTimeout(){ return timeout; } public void setTimeout(int timeout){
45 | P a g e

JAVA NETWORK MONITOR this.timeout = timeout; } public void setTimeout(String timeout){ log.debug("setTimeout(" + timeout + ")"); if(timeout != null){ setTimeout(Integer.parseInt(timeout)); } else { setTimeout(DEFAULT_TIMEOUT); } } public String getRequestData(){ return requestData; } public void setRequestData(String requestData){ this.requestData = requestData; } public String getExpression(){ return expression; } public void setExpression(String expression) throws MalformedPatternException{ this.expression = expression; this.pattern = compiler.compile(expression); } protected boolean test(JNMResponse response){ return true; } public void execute(){ String requestData = getRequestData(); TCPClient client = new TCPClient(host, port); client.setTimeout(getTimeout()); setLastRequest(new JNMRequest(requestData));
46 | P a g e

JAVA NETWORK MONITOR

try{ byte[] responseData = client.sendRequest(requestData); setLastResponse(new JNMResponse(responseData, System.currentTimeMillis())); } catch(InterruptedIOException e){ log.debug("Interrupted IO exception caught"); setLastResponse(null); setState(MonitorState.TIMEOUT); return; } catch(ConnectException e){ log.debug("Connection failed"); setLastResponse(null); setState(MonitorState.DOWN); return; } catch(Exception e){ log.debug("Exception caught"); setLastResponse(null); logError(e); setState(MonitorState.ERROR); return; } if(test(getLastResponse())){ setState(MonitorState.OK); } else { setState(MonitorState.FAILED); } } protected void readConfiguration(Configuration configuration) throws ConfigurationException{ try{
47 | P a g e

JAVA NETWORK MONITOR setHost(configuration.getChildValue("host")); setPort(configuration.getChildValue("port")); setTimeout(configuration.getChildValue("timeout")); setRequestData(configuration.getChildValue("request-data")); setExpression(configuration.getChildValue("expression", DEFAULT_EXPRESSION)); } catch(Exception e){ throw new ConfigurationException(e); } }protected void writeConfiguration(MutableConfiguration configuration) throws ConfigurationException{ configuration.addChild("host", getHost()); configuration.addChild("port", Integer.toString(getPort())); configuration.addChild("timeout", Integer.toString(getTimeout())); configuration.addChild("request-data", getRequestData()); configuration.addChild("expression", getExpression()); } /** Default timeout (20 seconds). */

public static final int DEFAULT_TIMEOUT = 30000; public static final String DEFAULT_EXPRESSION = ""; private static final Logger log = LogManager.getLogger(TCPMonitor.class.getName()); private Perl5Compiler compiler; private Perl5Matcher matcher; private Pattern pattern; private String host; private int port; private int timeout = DEFAULT_TIMEOUT; private String requestData; private String expression = DEFAULT_EXPRESSION;

}
48 | P a g e

Vous aimerez peut-être aussi