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 *     pierre
018 */
019package org.nuxeo.ecm.core.work;
020
021import org.nuxeo.ecm.core.work.api.Work;
022import org.nuxeo.runtime.api.Framework;
023import org.nuxeo.runtime.kv.KeyValueService;
024import org.nuxeo.runtime.kv.KeyValueStore;
025
026/**
027 * Work state helper to handle, out-of-API, distributed, work states.<br>
028 *
029 * @since 10.2
030 */
031public class WorkStateHelper {
032
033    protected static final String KV_NAME = "workManager";
034
035    protected static final String STATE_SUFFIX = ":state";
036
037    protected static final String CANCELED = "canceled";
038
039    protected static KeyValueStore getKeyValueStore() {
040        return Framework.getService(KeyValueService.class).getKeyValueStore(KV_NAME);
041    }
042
043    protected static Work.State getState(String workId) {
044        String stringState = getKeyValueStore().getString(getStateKey(workId));
045        return stringState == null || CANCELED.equals(stringState) ? null : Work.State.valueOf(stringState);
046    }
047
048    protected static String getStateKey(String workId) {
049        return workId + STATE_SUFFIX;
050    }
051
052    protected static boolean isCanceled(String workId) {
053        return CANCELED.equals(getKeyValueStore().getString(getStateKey(workId)));
054    }
055
056    protected static void setCanceled(String workId) {
057        getKeyValueStore().put(getStateKey(workId), CANCELED, 0);
058    }
059
060    protected static void setState(String workId, Work.State state, long ttl) {
061        getKeyValueStore().put(getStateKey(workId), state == null ? null : state.toString(), ttl);
062    }
063
064    private WorkStateHelper() {
065        // hide constructor
066    }
067
068}