001/*
002 * (C) Copyright 2018 Nuxeo (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 *       Kevin Leturc <kleturc@nuxeo.com>
018 */
019package org.nuxeo.ecm.automation.core.operations.services.bulk;
020
021import static java.lang.Boolean.FALSE;
022import static java.lang.Boolean.TRUE;
023
024import java.time.Duration;
025import java.util.concurrent.TimeoutException;
026
027import org.nuxeo.common.utils.ExceptionUtils;
028import org.nuxeo.ecm.automation.core.Constants;
029import org.nuxeo.ecm.automation.core.annotations.Context;
030import org.nuxeo.ecm.automation.core.annotations.Operation;
031import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
032import org.nuxeo.ecm.automation.core.annotations.Param;
033import org.nuxeo.ecm.core.api.CoreSession;
034import org.nuxeo.ecm.core.bulk.BulkService;
035
036/**
037 * Wait for Bulk computation. This operation is meant to be used for tests. Its usage in production is not recommended.
038 *
039 * @since 10.2
040 */
041@Operation(id = BulkWaitForAction.ID, category = Constants.CAT_SERVICES, label = "Wait for Bulk computation", since = "10.2", description = "Wait until Bulk computation is done. This operation is meant to be used for tests. Its usage in production is not recommended.", addToStudio = false)
042public class BulkWaitForAction {
043
044    public static final String ID = "Bulk.WaitForAction";
045
046    @Context
047    protected BulkService bulkService;
048
049    @Context
050    protected CoreSession repo;
051
052    @Param(name = "commandId")
053    protected String commandId;
054
055    @Param(name = "timeoutSecond", required = false)
056    protected long timeout = 60L;
057
058    @OperationMethod
059    public Boolean run() {
060        try {
061            if (!bulkService.await(commandId, Duration.ofSeconds(timeout))) {
062                throw new TimeoutException();
063            }
064        } catch (InterruptedException | TimeoutException e) {
065            if (ExceptionUtils.hasInterruptedCause(e)) {
066                // reset interrupted status
067                Thread.currentThread().interrupt();
068            }
069            return FALSE;
070        }
071        return TRUE;
072    }
073
074}