001/*
002 *  Copyright 2023 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.web.site;
017
018import java.util.List;
019import java.util.Map;
020import java.util.Optional;
021
022import org.apache.commons.lang3.StringUtils;
023import org.apache.http.NameValuePair;
024import org.apache.http.message.BasicNameValuePair;
025
026import org.ametys.core.ObservationConstants;
027import org.ametys.core.observation.AsyncObserver;
028import org.ametys.core.observation.Event;
029import org.ametys.core.user.UserIdentity;
030import org.ametys.runtime.plugin.component.AbstractLogEnabled;
031import org.ametys.runtime.servlet.RuntimeServlet;
032import org.ametys.web.cache.CacheHelper;
033
034/**
035 * Observer that transmit maintenance mode modifications to the front
036 */
037public class MaintenanceObserver extends AbstractLogEnabled implements AsyncObserver
038{
039    public boolean supports(Event event)
040    {
041        return event.getId().equals(ObservationConstants.EVENT_RUNTIME_MAINTENANCE)
042                && RuntimeServlet.getMaintenanceStatus() != RuntimeServlet.MaintenanceStatus.AUTOMATIC; // Changing to automatic can only happens at startup, and we want to avoid to call the front during startup 
043    }
044
045    public int getPriority(Event event)
046    {
047        return 0;
048    }
049
050    public void observe(Event event, Map<String, Object> transientVars) throws Exception
051    {
052        List<NameValuePair> params = List.of(
053            new BasicNameValuePair("status", RuntimeServlet.getMaintenanceStatus().toString()),
054            new BasicNameValuePair("comment", Optional.ofNullable(RuntimeServlet.getMaintenanceStatusForcedInformations()).map(s -> StringUtils.defaultString(s.comment())).orElse("")),
055            new BasicNameValuePair("initiator", Optional.ofNullable(RuntimeServlet.getMaintenanceStatusForcedInformations()).map(s -> UserIdentity.userIdentityToString(s.initiator())).orElse(""))
056        );
057        
058        CacheHelper.callWS("/set-maintenance-mode", params, getLogger());
059    }
060}