⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 profilertimerfilter.java

📁 mina是以Java实现的一个开源的网络程序框架
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
package org.apache.mina.filter.statistic;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoEventType;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;

/**
 * This class will measure the time it takes for a
 * method in the {@link IoFilterAdapter} class to execute.  The basic
 * premise of the logic in this class is to get the current time
 * at the beginning of the method, call method on nextFilter, and
 * then get the current time again.  An example of how to use
 * the filter is:
 *
 * <pre>
 * ProfilerTimerFilter profiler = new ProfilerTimerFilter(
 *         TimeUnit.MILLISECOND, IoEventType.MESSAGE_RECEIVED);
 * chain.addFirst("Profiler", profiler);
 * </pre>
 * 
 * The profiled {@link IoEventType} are :
 * <ul>
 * <li>IoEventType.MESSAGE_RECEIVED</li>
 * <li>IoEventType.MESSAGE_SENT</li>
 * <li>IoEventType.SESSION_CREATED</li>
 * <li>IoEventType.SESSION_OPENED</li>
 * <li>IoEventType.SESSION_IDLE</li>
 * <li>IoEventType.SESSION_CLOSED</li>
 * </ul>
 *
 * @author The Apache MINA Project (dev@mina.apache.org)
 * @version $Rev: 706057 $, $Date: 2008-10-19 21:40:20 +0200 (Sun, 19 Oct 2008) $
 * @org.apache.xbean.XBean
 */
public class ProfilerTimerFilter extends IoFilterAdapter {
    /** TRhe selected time unit */
    private volatile TimeUnit timeUnit;
    
    /** A TimerWorker for the MessageReceived events */
    private TimerWorker messageReceivedTimerWorker;
    
    /** A flag to tell the filter that the MessageReceived must be profiled */
    private boolean profileMessageReceived = false;

    /** A TimerWorker for the MessageSent events */
    private TimerWorker messageSentTimerWorker;

    /** A flag to tell the filter that the MessageSent must be profiled */
    private boolean profileMessageSent = false;

    /** A TimerWorker for the SessionCreated events */
    private TimerWorker sessionCreatedTimerWorker;

    /** A flag to tell the filter that the SessionCreated must be profiled */
    private boolean profileSessionCreated = false;

    /** A TimerWorker for the SessionOpened events */
    private TimerWorker sessionOpenedTimerWorker;

    /** A flag to tell the filter that the SessionOpened must be profiled */
    private boolean profileSessionOpened = false;

    /** A TimerWorker for the SessionIdle events */
    private TimerWorker sessionIdleTimerWorker;

    /** A flag to tell the filter that the SessionIdle must be profiled */
    private boolean profileSessionIdle = false;

    /** A TimerWorker for the SessionClosed events */
    private TimerWorker sessionClosedTimerWorker;

    /** A flag to tell the filter that the SessionClosed must be profiled */
    private boolean profileSessionClosed = false;

    /**
     * Creates a new instance of ProfilerFilter.  This is the
     * default constructor and will print out timings for
     * messageReceived and messageSent and the time increment
     * will be in milliseconds.
     */
    public ProfilerTimerFilter() {
        this(
                TimeUnit.MILLISECONDS, 
                IoEventType.MESSAGE_RECEIVED, IoEventType.MESSAGE_SENT);
    }
    
    /**
     * Creates a new instance of ProfilerFilter.  This is the
     * default constructor and will print out timings for
     * messageReceived and messageSent.
     * 
     * @param timeUnit the time increment to set
     */
    public ProfilerTimerFilter(TimeUnit timeUnit) {
        this(
        		timeUnit, 
                IoEventType.MESSAGE_RECEIVED, IoEventType.MESSAGE_SENT);
    }
    
    /**
     * Creates a new instance of ProfilerFilter.  An example
     * of this call would be:
     *
     * <pre>
     * new ProfilerTimerFilter(
     *         TimeUnit.MILLISECONDS,
     *         IoEventType.MESSAGE_RECEIVED, IoEventType.MESSAGE_SENT);
     * </pre>
     * 
     * Note : you can add as many {@link IoEventType} as you want. The method accepts
     * a variable number of arguments.
     * 
     * @param timeUnit Used to determine the level of precision you need in your timing.
     * @param eventTypes A list of {@link IoEventType} representation of the methods to profile
     */
    public ProfilerTimerFilter(TimeUnit timeUnit, IoEventType... eventTypes) {
        this.timeUnit = timeUnit;

        setProfilers(eventTypes);
    }
    
    /**
     * Create the profilers for a list of {@link IoEventType}.
     * 
     * @param eventTypes the list of {@link IoEventType} to profile
     */
    private void setProfilers(IoEventType... eventTypes) {
        for (IoEventType type : eventTypes) {
        	switch (type) {
	        	case MESSAGE_RECEIVED :
	        		messageReceivedTimerWorker = new TimerWorker();
	        		profileMessageReceived = true;
	        		break;

	        	case MESSAGE_SENT :
	        		messageSentTimerWorker = new TimerWorker();
	        		profileMessageSent = true;
	        		break;

	        	case SESSION_CREATED :
	        		sessionCreatedTimerWorker = new TimerWorker();
	        		profileSessionCreated = true;
	        		break;
	        		
	        	case SESSION_OPENED :
	        		sessionOpenedTimerWorker = new TimerWorker();
	        		profileSessionOpened = true;
	        		break;
	        		
	        	case SESSION_IDLE :
	        		sessionIdleTimerWorker = new TimerWorker();
	        		profileSessionIdle = true;
	        		break;
	        		
	        	case SESSION_CLOSED :
	        		sessionClosedTimerWorker = new TimerWorker();
	        		profileSessionClosed = true;
	        		break;
        	}
        }
    }

    /**
     * Sets the {@link TimeUnit} being used.
     *
     * @param timeUnit the new {@link TimeUnit} to be used.
     */
    public void setTimeUnit(TimeUnit timeUnit) {
    	this.timeUnit = timeUnit;
    }

    /**
     * Set the {@link IoEventType} to be profiled
     *
     * @param type The {@link IoEventType} to profile
     */
    public void profile(IoEventType type) {
    	switch (type) {
    		case MESSAGE_RECEIVED :
	    		profileMessageReceived = true;
	    		
	    		if (messageReceivedTimerWorker == null) {
	    			messageReceivedTimerWorker = new TimerWorker();
	    		}
    	    	
    	    	return;
    			
    		case MESSAGE_SENT :
	    		profileMessageSent = true;
	    		
	    		if (messageSentTimerWorker == null) {
	    			messageSentTimerWorker = new TimerWorker();
	    		}
    	    	
    	    	return;
    	    	
    		case SESSION_CREATED :
				profileSessionCreated = true;
	    		
	    		if (sessionCreatedTimerWorker == null) {
	    			sessionCreatedTimerWorker = new TimerWorker();
	    		}
    	    	
    		case SESSION_OPENED :
				profileSessionOpened = true;
	    		
	    		if (sessionOpenedTimerWorker == null) {
	    			sessionOpenedTimerWorker = new TimerWorker();
	    		}
    	    	
    		case SESSION_IDLE :
				profileSessionIdle = true;
	    		
	    		if (sessionIdleTimerWorker == null) {
	    			sessionIdleTimerWorker = new TimerWorker();
	    		}
    	    	
    		case SESSION_CLOSED :
				profileSessionClosed = true;
	    		
	    		if (sessionClosedTimerWorker == null) {
	    			sessionClosedTimerWorker = new TimerWorker();
	    		}
    	}
    }

    /**
     * Stop profiling an {@link IoEventType}
     *
     * @param type The {@link IoEventType} to stop profiling
     */
    public void stopProfile(IoEventType type) {
    	switch (type) {
			case MESSAGE_RECEIVED :
	    		profileMessageReceived = false;
		    	return;
				
			case MESSAGE_SENT :
				profileMessageSent = false;
		    	return;
		    	
			case SESSION_CREATED :
				profileSessionCreated = false;
				return;

			case SESSION_OPENED :
				profileSessionOpened = false;
				return;

			case SESSION_IDLE :
				profileSessionIdle = false;
				return;

			case SESSION_CLOSED :
				profileSessionClosed = false;
				return;
    	}
    }

    /**
     * Return the set of {@link IoEventType} which are profiled.
     *
     * @return a Set containing all the profiled {@link IoEventType} 
     */
    public Set<IoEventType> getEventsToProfile() {
    	Set<IoEventType> set = new HashSet<IoEventType>();
    	
    	if ( profileMessageReceived ) {
    		set.add(IoEventType.MESSAGE_RECEIVED);
    	}
    	
    	if ( profileMessageSent) {
    		set.add(IoEventType.MESSAGE_SENT);
    	}
    	
    	if ( profileSessionCreated ) {
    		set.add(IoEventType.SESSION_CREATED);
    	}
    	
    	if ( profileSessionOpened ) {
    		set.add(IoEventType.SESSION_OPENED);
    	}
    	
    	if ( profileSessionIdle ) {
    		set.add(IoEventType.SESSION_IDLE);
    	}
    	
    	if ( profileSessionClosed ) {
    		set.add(IoEventType.SESSION_CLOSED);
    	}
    	
        return set;
    }

    /**
     * Set the profilers for a list of {@link IoEventType}
     * 
     * @param eventTypes the list of {@link IoEventType} to profile
     */
    public void setEventsToProfile(IoEventType... eventTypes) {
        setProfilers(eventTypes);
    }

    /**
     * Profile a MessageReceived event. This method will gather the following
     * informations :
     * - the method duration
     * - the shortest execution time
     * - the slowest execution time
     * - the average execution time
     * - the global number of calls
     * 
     * @param nextFilter The filter to call next
     * @param session The associated session
     * @param message the received message
     */
    @Override
    public void messageReceived(NextFilter nextFilter, IoSession session,
            Object message) throws Exception {
    	if (profileMessageReceived) {
	        long start = timeNow();
	        nextFilter.messageReceived(session, message);
	        long end = timeNow();
	        messageReceivedTimerWorker.addNewDuration(end - start);
    	} else {
	        nextFilter.messageReceived(session, message);
    	}
    }

    /**
     * Profile a MessageSent event. This method will gather the following
     * informations :
     * - the method duration
     * - the shortest execution time
     * - the slowest execution time
     * - the average execution time
     * - the global number of calls
     * 
     * @param nextFilter The filter to call next
     * @param session The associated session
     * @param writeRequest the sent message
     */
    @Override
    public void messageSent(NextFilter nextFilter, IoSession session,
            WriteRequest writeRequest) throws Exception {
    	if (profileMessageSent) {
	        long start = timeNow();
	        nextFilter.messageSent(session, writeRequest);
	        long end = timeNow();
	        messageSentTimerWorker.addNewDuration(end - start);
    	} else {
	        nextFilter.messageSent(session, writeRequest);
    	}
    }

    /**
     * Profile a SessionCreated event. This method will gather the following
     * informations :
     * - the method duration
     * - the shortest execution time
     * - the slowest execution time
     * - the average execution time
     * - the global number of calls
     * 
     * @param nextFilter The filter to call next
     * @param session The associated session
     */
    @Override
    public void sessionCreated(NextFilter nextFilter, IoSession session)
            throws Exception {
    	if (profileSessionCreated) {
	        long start = timeNow();
	        nextFilter.sessionCreated(session);
	        long end = timeNow();
	        sessionCreatedTimerWorker.addNewDuration(end - start);
    	} else {
            nextFilter.sessionCreated(session);
    	}
    }

    /**
     * Profile a SessionOpened event. This method will gather the following
     * informations :
     * - the method duration
     * - the shortest execution time
     * - the slowest execution time
     * - the average execution time
     * - the global number of calls
     * 
     * @param nextFilter The filter to call next
     * @param session The associated session
     */
    @Override
    public void sessionOpened(NextFilter nextFilter, IoSession session)
            throws Exception {
    	if (profileSessionOpened) {
	        long start = timeNow();
	        nextFilter.sessionOpened(session);
	        long end = timeNow();
	        sessionOpenedTimerWorker.addNewDuration(end - start);
    	} else {
            nextFilter.sessionOpened(session);
    	}
    }

    /**
     * Profile a SessionIdle event. This method will gather the following
     * informations :
     * - the method duration
     * - the shortest execution time
     * - the slowest execution time
     * - the average execution time
     * - the global number of calls
     * 
     * @param nextFilter The filter to call next
     * @param session The associated session
     * @param status The session's status
     */
    @Override
    public void sessionIdle(NextFilter nextFilter, IoSession session,
            IdleStatus status) throws Exception {
    	if (profileSessionIdle) {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -