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 *     Funsho David
018 */
019
020package org.nuxeo.ecm.core.bulk;
021
022import static java.nio.charset.StandardCharsets.UTF_8;
023import static org.nuxeo.ecm.core.bulk.BulkComponent.BULK_KV_STORE_NAME;
024import static org.nuxeo.ecm.core.bulk.BulkServiceImpl.COMMAND;
025
026import java.io.IOException;
027
028import org.nuxeo.ecm.core.api.NuxeoException;
029import org.nuxeo.ecm.core.io.registry.MarshallerHelper;
030import org.nuxeo.ecm.core.io.registry.context.RenderingContext;
031import org.nuxeo.runtime.api.Framework;
032import org.nuxeo.runtime.kv.KeyValueService;
033import org.nuxeo.runtime.kv.KeyValueStore;
034
035/**
036 * Helper class for bulk commands.
037 *
038 * @since 10.2
039 */
040public class BulkCommands {
041
042    private BulkCommands() {
043        // utility class
044    }
045
046    public static BulkCommand fromKVStore(String commandId) {
047        KeyValueStore kvStore = Framework.getService(KeyValueService.class).getKeyValueStore(BULK_KV_STORE_NAME);
048        return fromKVStore(kvStore, commandId);
049    }
050
051    protected static BulkCommand fromKVStore(KeyValueStore kvStore, String commandId) {
052        byte[] data = kvStore.get(commandId + COMMAND);
053        return fromBytes(data);
054    }
055
056    public static BulkCommand fromBytes(byte[] data) {
057        String json = new String(data, UTF_8);
058        try {
059            return MarshallerHelper.jsonToObject(BulkCommand.class, json, RenderingContext.CtxBuilder.get());
060        } catch (IOException e) {
061            throw new NuxeoException("Invalid json bulkCommand=" + json, e);
062        }
063    }
064
065    public static byte[] toBytes(BulkCommand command) {
066        try {
067            return MarshallerHelper.objectToJson(command, RenderingContext.CtxBuilder.get()).getBytes();
068        } catch (IOException e) {
069            throw new NuxeoException("Unable to serialize the bulk command=" + command, e);
070        }
071    }
072}