001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software, please see the
018 * company website: http://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: http://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.ugc;
029
030/**
031 * A queue used to enforce a certain wait time between requests for sessions for the same form configuration.<p>
032 */
033public class CmsUgcSessionQueue {
034
035    /** True if the session queue is enabled. */
036    private boolean m_enabled;
037
038    /** The wait time between multiple session requests for the same configuration. */
039    private long m_interval;
040
041    /** The maximum number of threads waiting in the queue for the same configuration. */
042    private int m_maxLength;
043
044    /** The time at which the next thread should be scheduled to run. */
045    private long m_nextScheduleTime;
046
047    /** The number of threads waiting on this queue. */
048    private int m_waitCount;
049
050    /**
051     * Creates a new instance.<p>
052     *
053     * @param enabled true if the queue should be enabled
054     * @param interval the wait time to use between multiple session requests
055     * @param maxLength the maximum length of the queue
056     */
057    public CmsUgcSessionQueue(boolean enabled, long interval, int maxLength) {
058
059        m_enabled = enabled;
060        m_interval = interval;
061        m_maxLength = maxLength;
062        if (interval < 0) {
063            throw new IllegalArgumentException("Queue wait time must not be < 0");
064        }
065
066        if (maxLength < 0) {
067            throw new IllegalArgumentException("Queue maximum length must not be < 0");
068        }
069    }
070
071    /**
072     * Creates a session queue based on the given configuration.<p>
073     *
074     * @param config the configuration for which to create the session queue
075     * @return the newly created session queue
076     */
077    public static CmsUgcSessionQueue createQueue(CmsUgcConfiguration config) {
078
079        CmsUgcSessionQueue queue = new CmsUgcSessionQueue(
080            config.needsQueue(),
081            config.getQueueInterval().isPresent() ? config.getQueueInterval().get().longValue() : 0,
082            config.getMaxQueueLength().isPresent() ? config.getMaxQueueLength().get().intValue() : Integer.MAX_VALUE);
083        return queue;
084    }
085
086    /**
087     * Updates the queue parameters from the configuration object.<p>
088     *
089     * @param config the form configuration
090     */
091    public synchronized void updateFromConfiguration(CmsUgcConfiguration config) {
092
093        m_enabled = config.needsQueue();
094        m_interval = config.getQueueInterval().isPresent() ? config.getQueueInterval().get().longValue() : 0;
095        m_maxLength = config.getMaxQueueLength().isPresent()
096        ? config.getMaxQueueLength().get().intValue()
097        : Integer.MAX_VALUE;
098    }
099
100    /**
101     * If there are currently any threads waiting on this queue, wait for the interval given on construction after the currenly last thread stops waiting.<p>
102     *
103     * @return false if the queue was too long to wait, true otherwise
104     */
105    public synchronized boolean waitForSlot() {
106
107        if (!m_enabled) {
108            return true;
109        } else {
110            long now = System.currentTimeMillis();
111            long timeToWait = m_nextScheduleTime - now;
112            if (timeToWait <= 0) {
113                // This happens either if this method is called for the first time,
114                // or if the wait interval for the last thread to enter the queue has
115                // already fully elapsed
116                m_nextScheduleTime = now + m_interval;
117                return true;
118            } else if (m_waitCount >= m_maxLength) {
119                return false;
120            } else {
121                m_nextScheduleTime = m_nextScheduleTime + m_interval;
122                m_waitCount += 1;
123                try {
124                    // use wait here instead of sleep because it releases the object monitor
125
126                    // note that timeToWait can't be 0 here, because this case is handled in the first if() branch,
127                    // so wait() always returns after the given period
128                    wait(timeToWait);
129                } catch (InterruptedException e) {
130                    // TODO Auto-generated catch block
131                    e.printStackTrace();
132                }
133                m_waitCount -= 1;
134                return true;
135            }
136        }
137    }
138}