001/*
002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and others.
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 *
016 * Contributors:
017 *     <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
018 */
019
020package org.nuxeo.ecm.automation.core.operations.traces;
021
022import org.nuxeo.ecm.automation.OperationContext;
023import org.nuxeo.ecm.automation.core.Constants;
024import org.nuxeo.ecm.automation.core.annotations.Context;
025import org.nuxeo.ecm.automation.core.annotations.Operation;
026import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
027import org.nuxeo.ecm.automation.core.annotations.Param;
028import org.nuxeo.ecm.automation.core.trace.TracerFactory;
029import org.nuxeo.ecm.core.api.NuxeoPrincipal;
030import org.nuxeo.runtime.api.Framework;
031
032/**
033 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
034 * @since 5.8
035 */
036@Operation(id = AutomationTraceToggleOperation.ID, category = Constants.CAT_EXECUTION, label = "Traces.toggleRecording", description = "Toggle Automation call tracing (you can set the 'enableTrace' parameter if you want to explicitly set the traceEnable value", addToStudio = false)
037public class AutomationTraceToggleOperation {
038
039    public static final String ID = "Traces.ToggleRecording";
040
041    @Param(name = "enableTrace", required = false)
042    protected Boolean enableTrace = null;
043
044    /**
045     * @since 8.2
046     */
047    @Param(name = "readOnly", required = false)
048    protected Boolean readOnly = false;
049
050    @Context
051    protected OperationContext ctx;
052
053    protected boolean canManageTraces() {
054        NuxeoPrincipal principal = (NuxeoPrincipal) ctx.getPrincipal();
055        return principal != null && (principal.isAdministrator());
056    }
057
058    @OperationMethod
059    public boolean run() {
060        TracerFactory tracerFactory = Framework.getService(TracerFactory.class);
061        if (canManageTraces() && !readOnly) {
062            if (enableTrace == null) {
063                tracerFactory.toggleRecording();
064            } else {
065                if (enableTrace != tracerFactory.getRecordingState()) {
066                    tracerFactory.toggleRecording();
067                }
068            }
069        }
070        return tracerFactory.getRecordingState();
071    }
072}