001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.util;
016    
017    import com.liferay.portal.kernel.log.Log;
018    import com.liferay.portal.kernel.log.LogFactoryUtil;
019    
020    import java.lang.reflect.InvocationHandler;
021    import java.lang.reflect.Method;
022    
023    /**
024     * @author Michael C. Han
025     */
026    public class QueuingInvocationHandler implements InvocationHandler {
027    
028            public QueuingInvocationHandler(int capacity) {
029                    _methodHandlers = new LimitedFIFOQueue<>(capacity);
030            }
031    
032            public void flush() {
033                    if (_log.isDebugEnabled()) {
034                            _log.debug(
035                                    "Flush " + _methodHandlers.size() + " events from queue");
036                    }
037    
038                    _methodHandlers.clear();
039            }
040    
041            @Override
042            public Object invoke(Object proxy, Method method, Object[] args)
043                    throws Throwable {
044    
045                    MethodHandler methodHandler = new MethodHandler(method, args);
046    
047                    _methodHandlers.offer(methodHandler);
048    
049                    return null;
050            }
051    
052            public void invokeQueued(Object target) throws Exception {
053                    if (_log.isInfoEnabled()) {
054                            _log.info(
055                                    "Processing " + _methodHandlers.size() + " queued requests");
056                    }
057    
058                    MethodHandler methodHandler = null;
059    
060                    while ((methodHandler = _methodHandlers.poll()) != null) {
061                            methodHandler.invoke(target);
062                    }
063    
064                    if (_log.isInfoEnabled()) {
065                            _log.info("Completed processing queued requests");
066                    }
067            }
068    
069            private static final Log _log = LogFactoryUtil.getLog(
070                    QueuingInvocationHandler.class);
071    
072            private final LimitedFIFOQueue<MethodHandler> _methodHandlers;
073    
074    }