001/*
002 *  Copyright 2025 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.webanalytics.tracking;
017
018import org.apache.avalon.framework.service.ServiceException;
019import org.apache.avalon.framework.service.ServiceManager;
020import org.apache.cocoon.components.ContextHelper;
021import org.apache.cocoon.environment.Request;
022import org.quartz.JobExecutionContext;
023
024import org.ametys.core.schedule.progression.ContainerProgressionTracker;
025import org.ametys.plugins.core.impl.schedule.AbstractStaticSchedulable;
026import org.ametys.runtime.config.Config;
027import org.ametys.web.WebConstants;
028import org.ametys.web.analytics.WebAnalyticsHelper;
029import org.ametys.web.analytics.WebAnalyticsProvider;
030import org.ametys.web.repository.site.Site;
031import org.ametys.web.repository.site.SiteManager;
032
033/**
034 * Schedulable to send tracking information
035 */
036public class WebAnalyticsTrackingSchedulable extends AbstractStaticSchedulable
037{
038    /** Configuration key to know if sending stats is enabled */
039    public static final String SEND_STATS_CONFIG = "send-statistics-enable";
040    
041    /** The site manager */
042    protected SiteManager _siteManager;
043    
044    /** The web analytics helper */
045    protected WebAnalyticsHelper _webAnalyticsHelper;
046    
047    @Override
048    public void service(ServiceManager manager) throws ServiceException
049    {
050        super.service(manager);
051        _siteManager = (SiteManager) manager.lookup(SiteManager.ROLE);
052        _webAnalyticsHelper = (WebAnalyticsHelper) manager.lookup(WebAnalyticsHelper.ROLE);
053    }
054    
055    public void execute(JobExecutionContext context, ContainerProgressionTracker progressionTracker) throws Exception
056    {
057        // Send tracking information only is it's enable in the configuration
058        if (Config.getInstance().getValue(SEND_STATS_CONFIG, true, false))
059        {
060            Request request = ContextHelper.getRequest(_context);
061            for (Site site : _siteManager.getSites())
062            {
063                request.setAttribute(WebConstants.REQUEST_ATTR_SITE, site);
064                WebAnalyticsProvider provider = _webAnalyticsHelper.getSelectedProvider(site);
065                provider.sendTrackingInformation(site);
066            }
067        }
068    }
069}